开发者

Passing strings by value in C

I have two functions, one that creates a pointer to a string and another that manipulates it. I somehow am missing something critical, however:

int foo() {
   char * mystring; // Create pointer
   bar(&mystring); // Pass in address
   printf("%s\n", mystring);
   return 0; // There's a reason 开发者_开发问答for this
}

int bar(char ** mystring) {
   mystring[0] = malloc(strlen(mystring) + 1); // Since malloc will persist even after exiting bar
   *mystring = "hahaha"; // Dereference
   return 0; 
}

Any enlightenment for my addled brain would be greatly appreciated!


C doesn't have strings as first class values; you need to use strcpy() to assign strings.

strcpy(mystring[0], "hahaha");


In addition to the other answers given, note that:

mystring[0]

is the same as

*(mystring + 0)

which is the same as

*mystring

Your malloc allocates the memory and the pointer is written to mystring but it is overwritten by the next line.


The use of malloc is necessary, but this way: mystring[0] = malloc(strlen(mystring) + 1); is wrong, since you can't perform strlen on mystring(because it doesn't contain any string yet and because the pointer itself is not initialized). Allocate buffer with the size of your string. for example:

int bar(char ** mystring) {
   char* hello = "hahaha";
   *mystring = malloc(strlen(hello) + 1);
   strcpy(*mystring, hello);
   return 0; 
}

BTW, you could use the assignment *mystring = "hahaha"; without the malloc since this is a string stored in the data section, and the data will not be lost after returning from the function, but this way it is read-only data and you cannot modify it. The strcpy is there to copy the string to the allocated buffer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜