Ind*_*dri -5 c reference function c-strings dynamic-memory-allocation
我正在努力写一个char *作为参数传递。我想从函数write_char()向char *写一些字符串。使用以下代码,我遇到了分段错误。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void write_char(char* c){
c = (char*)malloc(11*(sizeof(char)));
c = "some string";
}
int main(){
char* test_char;
write_char(test_char);
printf("%s", test_char);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您有两个问题(与您尝试做的事情有关,还有其他问题):
C中的参数按值传递,这意味着参数变量(c在您的write_char函数中)是该函数中值的副本。修改此副本(如为其分配副本)将仅更改局部变量值,而不更改原始变量值。test_charmain
第二次分配给变量将覆盖变量中的当前值。如果你这样做
int a;
a = 5;
a = 10;
Run Code Online (Sandbox Code Playgroud)
您(希望)不知道为什么在第二个分配中将的值a更改为10。变量是指针不会改变该语义。
现在解决问题的方法...使函数返回指针可以轻松解决第一个问题。第二个问题可以通过将字符串复制到内存中而不是重新分配指针来解决。
所以我的建议是您编写类似
char *get_string(void)
{
char *ptr = malloc(strlen("some string") + 1); // Allocate memory, +1 for terminator
strcpy(ptr, "some string"); // Copy some data into the allocated memory
return ptr; // Return the pointer
}
Run Code Online (Sandbox Code Playgroud)
然后可以将其用作
char *test_string = get_string();
printf("My string is %s\n", test_string);
free(test_string); // Remember to free the memory we have allocated
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
190 次 |
| 最近记录: |