2010-06-06 120 views
0

这是我第一次在这里发布,希望我不会愚弄自己。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); 

} 

回答

1

*Buffer[2]是越来越理解为*(Buffer[2])。你想要的是(*Buffer)[2]

2

你的问题只是一个优先。该[]经营者有优先级数字是unary- *,所以行被解析,如果它是:

*(Buffer[2]) = 'A'; 

...这是不是你想要的。你真正想要的*先发生,所以你需要使用括号:

(*Buffer)[2] = 'A'; 

此外,您的通话strncpy()是错误的。如果复制的字符数等于长度,则strncpy()不会终止结果;并且由于你的记忆直接来自malloc(),所以那里可能没有终结者。 strncpy()实际上是您遇到的99.99%的案例中的错误工具 - 在本网站上搜索许多其他解释原因的答案。

strncat()的呼叫可以用来代替:

(*Buffer)[0] = '\0'; /* Truncate to an empty string */ 
strncat(*Buffer, Text, 5); 
+0

非常感谢! 和其他人一样。 :) – user359531 2010-06-06 05:15:24

1

的问题是,*Buffer[2]意味着*(Buffer[2]) - 你试图取消引用了错误的指针。你想使用(*Buffer)[2]