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 13-Jul-2009, 15:03
fairytales247 fairytales247 is offline
New Member
 
Join Date: Jul 2009
Posts: 15
fairytales247 has a little shameless behaviour in the past

Understanding how pointers are passed in a function.


I have been trying to understand how pointers are passed in a function which unfortunately the book that I am referring to doesn't completely explain for a dummie like me. Could you please help me simplify the things.

Here is a part of the code that will be of concern:

.....codes...

bool str_in(char **); /* Function prototype for str_in */

.....codes....
char *pS[NUM_P]; /* Array of string pointers */
int count = 0; /* Number of strings read */

1) if(!str_in(&pS[count])) /* Read a string */

.....codes.....
2) bool str_in(char **pString){

....codes..
*pString = (char*)malloc(strlen(buffer) + 1);

...codes...

}

So how are 1 and 2 linked?
1 passes the address but what does 2 recieve as argument?

(... just relating

*pString(recieves an address) = pS(which has the address)
*(*pString) = recieves what?

)

isn't &pS[count] the same as &*pS(count) the same as pS(count)?? This whole thing is really confusing. The more i think the more i get confused. lol

Any genius please help.

Thanks!
  #2  
Old 13-Jul-2009, 15:48
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 5,218
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: Understanding how pointers are passed in a function.


Quote:
Originally Posted by fairytales247
...so how...

Consider the following:
CPP / C++ / C Code:
char *pS[NUM_P];

Assuming NUM_P is #defined to be an integer constant, pS is an array of pointers to char. The array contains NUM_P members. Each member of the array is a variable whose data type is "pointer to char."

Suppose NUM_P is #defined to be 10, then

The variable pS[0] is a pointer to char
The variable pS[1] is a pointer to char
.
.
.
The variable pS[9] is a pointer to char

Now, suppose the variable count has a value of 1 then

the value of &pS[1] is the address of the variable pS[1]. That is to say, &pS[1] is a pointer to pS[1] and so the data type of &pS[1] is "pointer to pointer to char"

I hate to blow the punch line before the end, but here goes: By passing the address of pS[1] to the function, the function can change the value of pS[1].

Now, let's see what the heck is the point of all of this.


The function is defined to take a parameter that is "pointer to pointer to char", so the calling program can use &pS[count] as an argument.

Inside the function, since pString is a "pointer to pointer to char" we know that *pString is a pointer to char. In fact, if the function were called with &pS[1] as its argument, then inside the function, the value of *pString is equal to pS[1]. So the function is setting pS[1] to the value returned by malloc. That way, it can be used to hold the array of chars that you copy into that memory. And that will be seen as such back in the calling function

Bottom line:

In the C language, all arguments are passed by value. That is to say, a function is given its own copy of that variable to work with. Nothing that is done to that parameter in the function can change the value of that variable back in the main program. That's right: nothing.

In C, if you want a function to change the value of a variable back in the calling function corresponding to the function argument, you must pass a pointer to that variable.

CPP / C++ / C Code:
#include <stdio.h>
void foo(int x)
{
    x = 99;
    printf("    In foo: x = %d\n", x);
}

void bar(int *x)
{
    *x = 99;
    printf("    In bar:*x = %d\n",*x);
}

int main()
{
    int x = 42;
    printf("In main, initially: x = %d\n", x);
    foo(x);
    printf("In main, after foo: x = %d\n", x);
    bar(&x);
    printf("In main, after bar: x = %d\n", x);
    return 0;
}

Output:
Code:
In main, initially: x = 42 In foo: x = 99 In main, after foo: x = 42 In bar:*x = 99 In main, after bar: x = 99

Now, if you want a function to change the value of a pointer back in the calling function, you pass a pointer to the pointer. I'll do it with integers but the same applies to pointers to chars:

CPP / C++ / C Code:
#include <stdio.h>
void foo(int *px)
{
    px = NULL;

    printf("    In foo: px = %p\n", px);
}

void bar(int **px)
{
    *px = NULL;
    printf("    In bar:*px = %p\n",*px);
}

int main()
{
    int x = 42;
    int *px; /* pointer to int */
    px = &x;

    printf("In main, initially: px = %p\n", px);
    foo(px);
    printf("In main, after foo: px = %p\n", px);
    bar(&px); /* pointer to pointer to int */
    printf("In main, after bar: px = %p\n", px);
    return 0;
}

Output (using GNU compiler)
Code:
In main, initially: px = 0xbffd48e0 In foo: px = (nil) In main, after foo: px = 0xbffd48e0 In bar:*px = (nil) In main, after bar: px = (nil)

Other compilers may print a zero value instead of the (nil) for the NULL pointer, but the results are the same.

Summary A function can not change the value of an argument in the calling function, but if you pass a pointer, the function can change whatever it points to.


Regards,

Dave
  #3  
Old 13-Jul-2009, 23:04
Howard_L Howard_L is online now
Regular Member
 
Join Date: Apr 2007
Location: Maryland/PA, USA
Posts: 803
Howard_L is a jewel in the roughHoward_L is a jewel in the roughHoward_L is a jewel in the rough

Re: Understanding how pointers are passed in a function.


Quote:
This whole thing is really confusing. The more i think the more i get confused.
Echo that dude , but it get's easier with practice.
Just the other day you were beginning with pointers and array referencing.
Somhow you're now jumping way ahead to passing some pretty sophisticated references.
No wonder you'r cornfused...
Just remember that your referring to addresses i memory.
Requesting the address of an object , passing that address , requesting a value found at that address , etc.
Understanding memory, storage and refencing is key to being a good programmer.
You can learn a lot from playing around with simple 1 byte referencing examples like this:
CPP / C++ / C Code:
#include <stdio.h>

int main(void)
{
  char *cptr, s[32] = " once upon a time... ";  /* cptr is a pointer to type char (1 byte) */
  int i, j = 7;

  /****/
  printf("\nHere is how printf %%s works: \n");

  cptr = s;
  while( *cptr != 0 )
    putchar( *cptr++ );  /*note that pointer is incremented to next location */

  /****/
  /* cptr =  s; */
  cptr =  (void*)&j;    /* here I cast the address of j to type void* so compiler doesn't complain */

  printf("\nAddress of: s= %p,  i= %p,  j= %p  cptr= %p \n\n",
          (void*)s, (void*)&i, (void*)&j, (void*)cptr );

  printf("     Address    Char  Hex \n");

  for(i = 0; i < 35; i++)  /* safety loop */
  {
    printf("%2d: %p  '%c'   %02x,  \n", i, (void*)cptr, *cptr, *cptr );
    cptr++;  /* pointer incrementation ("pointer math" functionality) */
  }
  return 0;
}
And here's another example passing the address of a c_string to a function:
CPP / C++ / C Code:
#include <stdio.h>

int print_cstr(char* s)
{
  char *sp = s;   /* set pointer to begining of char array */
  int i, j; 
  
  /* do one straight print of string one char at a time */
  for(i = 0; *sp != 0; i++ )
      putchar( *sp++ );     /* this does not change  s in main() in any way */

  /* now take a look at the addresses */
  sp = s;  /* reset pointer to begining of char array */
  putchar(0x0a);
  putchar(0x0a);
  for(j = 0; j < i; j++, sp++)
    printf("%2d: %p    %c    %02x \n", j, sp, *sp, *sp );
  
  return i;
}

int main(void)
{         
  char s[16] = "Howdy Doody";
  int i;

  printf("\nAddress of s is: %p \nThe print_cstr() fuction prints:\n", s);

  i = print_cstr(s);  /* pass the address of the beginning of the array */
  
  printf("%d letters printed \n", i);
  
  return 0;
}  
Tryit , poke at it a bit , see if what happens is as you expected...
See if you don't get a better sense of your place memory and in the universe...
Here is a very good tutorial which helped me a bunch:
A TUTORIAL ON POINTERS AND ARRAYS IN C by Ted Jensen
Last edited by Howard_L : 14-Jul-2009 at 00:17.
  #4  
Old 13-Jul-2009, 23:13
fairytales247 fairytales247 is offline
New Member
 
Join Date: Jul 2009
Posts: 15
fairytales247 has a little shameless behaviour in the past
Thumbs up

Re: Understanding how pointers are passed in a function.


A big bunch of thanks to Dave and Howard
That is a great help.
 
 

Recent GIDBlogProgramming ebook direct download available 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
run script command on ns2.26 newbie06 Computer Software Forum - Linux 65 19-Aug-2009 08:50
Problem executing nam-1.13 RodolfoAlvizu Computer Software Forum - Linux 20 28-Feb-2009 16:23
[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 19:57.


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