我通過使用一個非常簡單的程序熟悉了C字符串和指針。爲什麼我必須通過引用傳遞字符串才能更改其指向的位置?
這個版本,它通過引用傳遞一個字符串,作品:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void test(char **string) {
*string = (char *)malloc(5);
char *temp = "hell";
strcpy(*string, temp);
}
int main(int argc, char *argv[]) {
char *string = NULL;
test(&string);
printf("%s\n", string);
return 0;
}
它打印出 「地獄」。
這個版本,它只是按值傳遞的字符串,不工作,並因此導致segfault:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void test(char *string) {
string = (char *)malloc(5);
char *temp = "hell";
strcpy(string, temp);
}
int main(int argc, char *argv[]) {
char *string = NULL;
test(string);
printf("%s\n", string);
return 0;
}
據我所知,第一個版本是有道理的,因爲我傳遞的地址字符串的地址。因此,當我解引用這個雙指針時,我得到了字符串的真實地址,並可以用malloc重新分配它。
然而,第二個版本我不清楚它爲什麼不起作用。在這個版本中,我將字符串的地址傳遞給測試函數。我讀過C中的所有東西都是按值傳遞的,但是這些數組名稱實際上是地址。這是否意味着我將字符串的實際地址傳入測試?難道事情不一樣嗎?我很困惑,請幫助我。
出於同樣的原因,如果你想改變它的值,你需要通過引用傳遞'int'。 – juanchopanza
C使用[傳遞值](http://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value) –