Passing a char pointer

Programming, for all ages and all languages.
Post Reply
chris

Passing a char pointer

Post by chris »

How come when I pass a char pointer to a function and get it to point to a certain place in another char pointer that I passed to that same function, when I return to the calling function, the work that was done in the called function didn't affect my pointer? Do I need to use pointers to pointers?

I've tried it with pointers to pointers but it doesn't work

Code: Select all

parse_pipes(bufp, pipes, npipes, nextpipe, &flags)

Code: Select all

int
parse_pipes(char *buf, int (*pipes)[2], int npipes, char *nextpipe, int *flags)
{
   if (npipes > 0)
      *flags |= P_READ;
   if ((nextpipe = strchr(buf, '|')) != NULL) {
      *nextpipe++ = 0;
      if (pipe(pipes[npipes]) < 0)
         return(-1);
      *flags |= P_WRITE;
      if (strlen(buf) < 1)
         return(-1);
   }
   return(0);
}

Code: Select all

[Aurora:~/dev/c] chris% ./shell
> ls | cd
np:  cd
> bp: ls 
np: (null)
np = char *nextpipe
bp = bufp

As you can see, my problem is that when I print nextpipe from the caller, it's still NULL and not where I pointed it to in parse_pipes. It doesn't make sense because I modify bufp yet it works properly.
srtyh

Re:Passing a char pointer

Post by srtyh »

"How come when I pass a char pointer to a function" (lets call it char *a)

"and get it to point to a certain place in another char pointer" (lets call it char *b, leading to *a=*b)

"when I return to the calling function, the work that was done in the called function didn't affect my pointer?" (most likely you are trying a=b)

"Do I need to use pointers to pointers?" (sth like char **a, char *b, and *a=b ?)
chris

Re:Passing a char pointer

Post by chris »

strchr() is setting nextpipe to a certain place in buf (or bufp in the caller), and it's a standard library function, so I'm guessing it's doing it properly.
chris

Re:Passing a char pointer

Post by chris »

Problem solved:

Code: Select all

 int
parse_pipes(char *buf, int (*pipes)[2], int npipes, char **nextpipe, int *flags)
{
   if (npipes > 0)
      *flags |= P_READ;
   if ((*nextpipe = strchr(buf, '|')) != NULL) {
      **nextpipe = 0; 
      (*nextpipe)++;
      if (pipe(pipes[npipes]) < 0)
         return(-1);
      *flags |= P_WRITE;
      if (strlen(buf) < 1)
         return(-1);
   }
   return(0);
}
Post Reply