我是 C 新手,我花了 2 个小时才解决这个问题。
void helper(char* a, char* b){
a = malloc(strlen(b));
memcpy(a, b, strlen(b));
printf("%s %s\n", a, b);
}
int main(){
char* b = "hello";
char* a;
helper(a, b);
printf("%s", a);
}
而a
始终为null
。有什么我错过的吗?
最佳答案
在main()
中,a
和b
是指针。
helper(a, b);
向 helper() 提供指针
作为调用 a
的副本和指针 b
的副本helper()
的一部分。
函数完成。
调用 helper(a, b)
不会更新/更改 main()
中的 a
。 b
也没有改变。
代码需要一种新方法,其中有几种好的方法。示例:使用 helper2()
的返回值。
char *helper2(const char *source);
int main(void) {
const char* b = "hello";
char* a = helper2(b);
printf("<%s>", a);
free(a);
}
现在创建helper2()
。代码模板如下:
#include <...> // whats includes are needed.
#include <...>
char *helper2(const char *source) {
size_t size_needed = ....; // length + 1 for the null character
char *destination = ...' // allocate
if (destination ...) { // Successful allocation?
memcpy(destination, ...., ...); // copy - include null character
}
return ... // What should be returned here?
}
关于c - 如何将字符串分配给 char* 指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41175504/