开发者

Changing a char array's values

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 arr开发者_如何学JAVAay's values?


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜