更改字符数组的值

发布于 2024-11-06 21:22:15 字数 273 浏览 1 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

风尘浪孓 2024-11-13 21:22:15

您将 foo 设置为指向字符串文字(“testing”)而不是您分配的内存。因此,您试图更改常量的只读内存,而不是分配的内存。

这是正确的代码:

char* foo = malloc(sizeof(char)*50);
strcpy(foo,"testing");

甚至

cont int MAXSTRSIZE = 50;
char* foo = malloc(sizeof(char)*MAXSTRSIZE);
strncpy(foo,"testing",MAXSTRSIZE);

可以更好地防止缓冲区溢出漏洞。

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:

char* foo = malloc(sizeof(char)*50);
strcpy(foo,"testing");

or even better

cont int MAXSTRSIZE = 50;
char* foo = malloc(sizeof(char)*MAXSTRSIZE);
strncpy(foo,"testing",MAXSTRSIZE);

to protect against buffer over-run vulnerability.

高冷爸爸 2024-11-13 21:22:15

您的问题是您正在更改指针引用。

通过这样做:

char* foo = (char*) malloc(sizeof(char)*50); foo = "testing";

您将 foo pointer 分配给存储在某处的 "testing" 字符串(我猜是运行时错误),而不是新分配的空间。

希望这会有所帮助

Your problem is that you are changing the pointer reference.

By doing :

char* foo = (char*) malloc(sizeof(char)*50); foo = "testing";

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

-小熊_ 2024-11-13 21:22:15

对于字符串,您不应通过赋值运算符 (=) 为其赋值。这是因为字符串不是实际类型,它们只是字符指针。相反,您必须使用strcpy

您的代码的问题是您已经为 foo 分配了内存,然后您将 foo 重新分配给了另一个只读内存地址。当您分配给 foo[0] 时,您会收到运行时错误,因为您正在尝试写入只读内存。

通过执行以下操作修复您的代码:

char* foo = malloc(50);
strcpy(foo, "testing");

这有效,因为 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 use strcpy.

The problem with your code is that you have allocated memory for foo, then you reassign foo to a different memory address that is READONLY. When you assign to foo[0] you get a runtime error because you are trying to write to readonly memory.

Fix your code by doing this:

char* foo = malloc(50);
strcpy(foo, "testing");

This works because foo points to the address that you allocated.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文