这是我第一次在这里发布,希望我不会愚弄自己。C:正确的语法分配内存使用指针指针
我想使用一个函数来分配内存到指针,将文本复制到缓冲区,然后更改一个字符。我不断收到段错误,并试图查找答案,我的语法可能是错误的,我可以使用一些启发。
/* My objective is to pass a buffer to my Copy function, allocate room, and copy text to it. Then I want to modify the text and print it.*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int Copy(char **Buffer, char *Text);
int main()
{
char *Text = malloc(sizeof(char) * 100);
char *Buffer;
strncpy(Text, "1234567890\n", 100);
Copy(&Buffer, Text);
}
int Copy(char **Buffer, char *Text)
{
int count;
count = strlen(Text)+1;
*Buffer = malloc(sizeof(char) * count);
strncpy(*Buffer, Text, 5);
*Buffer[2] = 'A'; /* This results in a segfault. "*Buffer[1] = 'A';" results in no differece in the output. */
printf("%s\n", *Buffer);
}
非常感谢! 和其他人一样。 :) – user359531 2010-06-06 05:15:24