這是我第一次在這裏發佈,希望我不會愚弄自己。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