[英]C: Proper syntax for allocating memory using pointers to pointers
This is my first time posting here, hopefully I will not make a fool of myself. 这是我第一次在这里发帖,希望我不会自欺欺人。
I am trying to use a function to allocate memory to a pointer, copy text to the buffer, and then change a character. 我正在尝试使用一个函数将内存分配给指针,将文本复制到缓冲区,然后更改字符。 I keep getting a segfault and have tried looking up the answer, my syntax is probably wrong, I could use some enlightenment.
我不断遇到段错误,并尝试查找答案,我的语法可能是错误的,我可以使用一些启示。
/* 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);
}
Your problem is simply one of precedence. 您的问题只是优先事项之一。 The
[]
operator has higher precendence that unary- *
, so the line is parsed as if it was: []
运算符具有比unary- *
更高的优先级,因此该行被解析为:
*(Buffer[2]) = 'A';
...which is not what you want. ...这不是您想要的。 You actually want the
*
to happen first, so you need to use parantheses: 您实际上希望
*
首先出现,所以您需要使用括号:
(*Buffer)[2] = 'A';
Additionally, your strncpy()
call is wrong. 此外,您的
strncpy()
调用是错误的。 strncpy()
does not nul-terminate the result if the number of characters copied is equal to the length; 如果复制的字符数等于长度,则
strncpy()
不会使结果终止。 and since your memory comes straight from malloc()
, there may not be a nul-terminator there already. 并且由于您的内存直接来自
malloc()
,因此可能还没有nul终止符。 strncpy()
is actually the wrong tool in 99.99% of the cases that you will encounter - search on this site for numerous other answers explaining why. 在99.99%的情况下,
strncpy()
实际上是错误的工具-在此站点上搜索许多其他答案以解释原因。
A call to strncat()
can be used instead: 可以使用对
strncat()
调用来代替:
(*Buffer)[0] = '\0'; /* Truncate to an empty string */
strncat(*Buffer, Text, 5);
*Buffer[2]
is getting interpreted as *(Buffer[2])
. *Buffer[2]
被解释为*(Buffer[2])
。 What you want is (*Buffer)[2]
. 您想要的是
(*Buffer)[2]
。
The problem is that *Buffer[2]
means *(Buffer[2])
- you're trying to dereference the wrong pointer. 问题在于
*Buffer[2]
意思是*(Buffer[2])
-您正试图取消引用错误的指针。 You want to use (*Buffer)[2]
. 您想使用
(*Buffer)[2]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.