GIDForums  

Go Back   GIDForums > Computer Programming Forums > C Programming Language
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 12-Jul-2009, 12:48
fairytales247 fairytales247 is offline
New Member
 
Join Date: Jul 2009
Posts: 15
fairytales247 has a little shameless behaviour in the past

Simple but very confusing, help on pointer please


As doing this pointer thing (which has made me realize the power of C over Java) i think i am understanding but at times it just pisses me off as i can't find the solution to some confusing porblems. Here is one that has been troubling me for a while, actually 2 days. Plz Plz enlighten me anyone genius.

So first of all I made a simple program just to know what arrays of pointers do.

CPP / C++ / C Code:
#include<stdio.h>

//test of arrays of pointers

int main(void){
	
	char st[2] = {'A','B'};
	char *pst[2] = {NULL};
	pst[0] = st;
	pst[1] = &st[1];
	
	printf("%p value in st\n",st);
	printf("%p value in &st\n",&st);
	printf("%p value in pst\n",pst);
	printf("%p value in &pst\n",&pst);
	printf("%p value in &pst0\n",&pst[0]);
	printf("%p value in &ps1\n",&pst[1]);
	printf("%p value in pst0\n",pst[0]);
	printf("%p value in pst1\n",pst[1]);
	printf("%c value pointed by pst0\n",*pst[0]);
	printf("%c value pointed by pst1\n",*pst[1]);
	printf("%c value in pst1\n",pst[1]); //converts the hexadecimal to                                                      //character format hehe
}


This program clearly tell me that pst[1] has the address of the variable st[1].
and onle *pst[1] has the value contained in st[1] i.e B.

----------------------------------------------------------
See the output of the program below
--------------------------------------------------------

D:\prog\cfiles\pointers>try4
0022FF46 value in st
0022FF46 value in &st
0022FF38 value in pst
0022FF38 value in &pst
0022FF38 value in &pst0
0022FF3C value in &ps1
0022FF46 value in pst0
0022FF47 value in pst1
A value pointed by pst0
B value pointed by pst1
G value in pst1

-----------------------------------------------

Then again and again i see the program in a tutorial lesson and can't reason why. see the code first (it works fine, i have tested it)

CPP / C++ / C Code:


/* Program 7.12 Arrays of Pointers to Strings */
#include <stdio.h>
const size_t BUFFER_LEN = 512;                /* Size of input buffer     */
int main(void)
{
  char buffer[BUFFER_LEN];                    /* Store for strings        */
  [b]char *pS[3] = { NULL }; [/b]                    /* Array of string pointers */
  char *pbuffer = buffer;                     /* Pointer to buffer        */
  size_t index = 0;                           /* Available buffer position*/
  printf("\nEnter 3 messages that total less than %u characters.",
                                                           BUFFER_LEN-2);
  /* Read the strings from the keyboard */
  for(int i=0 ; i<3 ; i++)
  {
    printf("\nEnter %s message\n", i>0? "another" : "a" );
    [b]pS[i] = &buffer[index];        [/b]         /* Save start of string         */
    /* Read up to the end of buffer if necessary */
    for( ; index<BUFFER_LEN ; index++)      /* If you read \n ... */
      if((*(pbuffer+index) = getchar()) == '\n')
        {
          *(pbuffer+index++) = '\0';        /* ...substitute \0   */
          break;
        }

		/* Check for buffer capacity exceeded */
    if((index == BUFFER_LEN) && ((*(pbuffer+index-1) != '\0') || (i<2)))
    {
      printf("\nYou ran out of space in the buffer.");
      return 1;
    }
  }
  printf("\nThe strings you entered are:\n\n");
  for(int i = 0 ; i<3 ; i++)
    [b]printf("%s\n", pS[i]);[/b]
  printf("The buffer has %d characters unused.\n",
                     BUFFER_LEN-index);
  return 0;
}

So I have highlighted the problem. Why in the world does the the statement

printf("%s\n", pS[i]);

print the value it points to rather than the value it has.

See the output below
----------------------------------------------------------

Enter a message
Hello World!
Enter another message
Today is a great day for learning about pointers.
Enter another message
That's all.
The strings you entered are:
Hello World!
Today is a great day for learning about pointers.
That's all.
The buffer has 437 characters unused.

------------------------------------------------------------

I know I am missing something small yet crucial here. Thats for sure as it has just been few days that i m learning C and I know many of them say that pointers are scary.

Could you help me please.

Thank you
Last edited by LuciWiz : 12-Jul-2009 at 12:51. Reason: Please insert your C code between [cpp] & [/cpp] tags
  #2  
Old 12-Jul-2009, 15:33
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 5,217
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Simple but very confusing, help on pointer please


Quote:
Originally Posted by fairytales247
So I have highlighted the problem. Why in the world does the the statement

printf("%s\n", pS[i]);

print the value it points to rather than the value it has.

That's the way that "%s" works.

If you have a pointer to char, say x, then, as you know, the following prints the byte value of the pointer in hexadecimal:

CPP / C++ / C Code:
printf("%p", x);

However the "%s" format specifier is used to print out the sequence of chars starting at the address given by the value of x and continuing until a zero byte is found. It does not print the zero byte.

So, suppose str is a pointer variable, and you do the following:
CPP / C++ / C Code:
printf("%s", str);
It goes to the memory location whose address is the value of the pointer str and starts spewing characters to the output stream. It continues sequentially through memory until it encounters a byte whose bits are all zero. It stops there. (It doesn't put the zero byte to the output stream.)


As a matter of convenient notation, it is extremely important to note the following:

If p has a pointer data type and i hass an integer data type the following two notations have exactly the same meaning:

CPP / C++ / C Code:
*(p+i)

is exactly the same as

CPP / C++ / C Code:
p[i]

I don't mean 'pretty much the same as," or "more-or-less equivalent to," or "for practical purposes the same as," I mean "absolutely, positively, completely, exactly the same as."




Consider
CPP / C++ / C Code:
    int x[100];
This reserves enough contiguous memory to hold 100 int variables.

The address of the first element (element zero) in the array is
CPP / C++ / C Code:
&x[0];

Note that the name of any array is defined to be a constant pointer whose value is the address of the first element in the array, so the following is also equal to the address of the first element of the array
CPP / C++ / C Code:
x

The address of the next element of the array is
CPP / C++ / C Code:
&x[1]

The following is also the address of that element
CPP / C++ / C Code:
x+1

If I want to print the int value of that element I could do
CPP / C++ / C Code:
    printf("%d", x[1]);

or

CPP / C++ / C Code:
    printf("%d", *(x+1));

You can use either notation. The results are exactly the same.

Bottom line: With printf, "%s" expects a pointer to char as an argument. It prints the character contents of memory in sequence, starting at the pointer value, and continuing until it sees a byte all of whose bits are zero. It stops there (without putting the zero byte to the output stream).

Other format specifiers, such as "%d", "c,", "%f", "%x", "%p", etc., expect a variable as an argument and the print statement prints the numeric value of that variable in the specified format.


Regards,

Dave
Last edited by davekw7x : 12-Jul-2009 at 16:14.
  #3  
Old 12-Jul-2009, 23:02
fairytales247 fairytales247 is offline
New Member
 
Join Date: Jul 2009
Posts: 15
fairytales247 has a little shameless behaviour in the past
Thumbs up

Re: Simple but very confusing, help on pointer please


Great help, certainly enlightening. How could I miss that.

Thank you Dave.
  #4  
Old 13-Jul-2009, 09:37
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 5,217
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Simple but very confusing, help on pointer please


Quote:
Originally Posted by fairytales247
... How could I miss that...

It was a very good question. Even though books and tutorials cover such things (some do a better job than others), many people don't take the time and make the effort to test it on their own.

I think that working from specific examples of your own creation is probably the best way to nail things down.

After all, no one was born knowing this stuff, right?

Regards,

Dave
 
 

Recent GIDBlogAccepted for Ph.D. program by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
MACRO to detect big / little endian ahbi82 C Programming Language 14 26-Aug-2007 11:33
Confusing Pointer Golmal C Programming Language 3 08-Sep-2006 02:22
[Tutorial] Pointers in C (Part II) Stack Overflow C Programming Language 0 27-Apr-2005 18:36
[Tutorial] Pointers in C (Part I) Stack Overflow C Programming Language 1 08-Apr-2005 19:35

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 07:42.


vBulletin, Copyright © 2000 - 2009, Jelsoft Enterprises Ltd.