更改字符数组的值
char* foo = (char*) malloc(sizeof(char)*50); foo = "testing";
在 C 中,我可以看到该字符串的第一个字符:
printf("%c",foo[0]);
但是当我尝试更改该值时:
foo[0]='f'
它在运行时给出错误。
我如何更改这个动态分配的 char 数组的值?
char* foo = (char*) malloc(sizeof(char)*50); foo = "testing";
In C, i can see the first character of that string :
printf("%c",foo[0]);
But when i try to change that value :
foo[0]='f'
It gives error in runtime.
How can i change this, dynamically allocated, char array's values?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您将 foo 设置为指向字符串文字(
“testing”
)而不是您分配的内存。因此,您试图更改常量的只读内存,而不是分配的内存。这是正确的代码:
甚至
可以更好地防止缓冲区溢出漏洞。
You are setting foo to point to the string literal (
"testing"
) not the memory you allocated. Thus you are trying to change the read only memory of the constant, not the allocated memory.This is the correct code:
or even better
to protect against buffer over-run vulnerability.
您的问题是您正在更改指针引用。
通过这样做:
您将 foo pointer 分配给存储在某处的
"testing"
字符串(我猜是运行时错误),而不是新分配的空间。希望这会有所帮助
Your problem is that you are changing the pointer reference.
By doing :
You are assigning the foo pointer to the
"testing"
string that is stored somewhere (hens the runtime error i guess), not to the newly allocated space.Hope this will help
对于字符串,您不应通过赋值运算符 (
=
) 为其赋值。这是因为字符串不是实际类型,它们只是字符指针。相反,您必须使用strcpy
。您的代码的问题是您已经为
foo
分配了内存,然后您将foo
重新分配给了另一个只读内存地址。当您分配给foo[0]
时,您会收到运行时错误,因为您正在尝试写入只读内存。通过执行以下操作修复您的代码:
这有效,因为
foo
指向您分配的地址。With strings, you shouldn't assign their values via the assignment operator (
=
). This is because strings aren't an actual type, they are just char pointers. Instead, you have to usestrcpy
.The problem with your code is that you have allocated memory for
foo
, then you reassignfoo
to a different memory address that is READONLY. When you assign tofoo[0]
you get a runtime error because you are trying to write to readonly memory.Fix your code by doing this:
This works because
foo
points to the address that you allocated.