Hi all, this is my first post!

I'm pretty new to C and maybe this is a dumb question.
I've a function that accept a string as a parameter for modify it but it doesn't (I'm sure there is some logical mistake with pointers):

void doSomething(char *string)
{
    string = "some string";
}

That I call whith this:

char *origString = NULL;
doSomething(origString);
printf("\n%s\n", origString);

And the output is:

<NULL>

So I suppose the there is something wrong in the assignement in the function but i cannot solve this.

Thanks for the help and sorry for my *very* bad english!

NiNTNEDU.

Recommended Answers

All 2 Replies

Every function parameter is passed by value in C. Pass by value means that a copy of the value is made and you access the copy from within the function. For example:

#include <stdio.h>

void foo ( int bar )
{
  printf ( "%p\n", (void*)&bar );
}

int main ( void )
{
  int bar;

  printf ( "%p\n", (void*)&bar );
  foo ( bar );

  return 0;
}

The addresses are different. You can simulate the effect of passing by reference (that is, passing an alias for the actual object) with pointers, but pointers are still passed by value:

#include <stdio.h>

void foo ( int *bar )
{
  printf ( "%p\n", (void*)&bar );
}

int main ( void )
{
  int *bar;

  printf ( "%p\n", (void*)&bar );
  foo ( bar );

  return 0;
}

bar is a pointer, but the addresses are still different. That's because the bar from main and the bar from foo are two separate entities. At this point you have enough information to understand what's wrong in your code.

What happens is you pass a copy of the pointer to doSomething and then assign to the copy, but the original is still unchanged. The solution when you want to pass by reference is to simulate it with a pointer, even if the original object is already a pointer:

#include <stdio.h>

void doSomething ( char **string )
{
  *string = "some string";
}

int main ( void )
{
  char *origString = NULL;

  doSomething ( &origString );
  printf ( "%s\n", origString );

  return 0;
}

You want to change what the pointer points to, so the pointer must be passed by "reference" to doSomething.

commented: Great explaination :) +31

Ahhh, awesone!

Your explanation is really beautiful and clear, now I understand!

Thanks, thanks, thanks!

I'll print your post for future reference!

Greetings,

NiNTENDU.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.