好吧,我試圖將字符指針傳遞給另一個函數。我可以用char數組做這個,但不能用char指針來做。問題是我不知道它的大小,所以我不能在main()
函數中聲明關於大小的任何信息。在C中傳遞字符指針
#include <stdio.h>
void ptrch (char * point) {
point = "asd";
}
int main() {
char * point;
ptrch(point);
printf("%s\n", point);
return 0;
}
然而,這並不正常工作,這兩部作品:
1)
#include <stdio.h>
int main() {
char * point;
point = "asd";
printf("%s\n", point);
return 0;
}
2)
#include <stdio.h>
#include <string.h>
void ptrch (char * point) {
strcpy(point, "asd");
}
int main() {
char point[10];
ptrch(point);
printf("%s\n", point);
return 0;
}
所以我試圖瞭解原因和可能的解決我的問題
哪種方式更便宜? –
@SarpKaya都非常快速(如果有的話,差異會很小),但我更喜歡「返回指針」方法以提高可讀性。 –
如果您不將返回值硬編碼爲字符串文字,將觸發局部變量的警告。 – Zimano