user12973562
user12973562

Reputation:

Overwriting a char[ ] in C

I'm a CS student and I'm trying to figure out pointers in C. I have:

char atest[] = "this is a test";

it prints, all is well.

Then I'm trying to do:

atest[] = "atest is now changed";

and it won't let me. Why? Can I never change a char[] without using a function?

Thanks all

Upvotes: 0

Views: 87

Answers (2)

Tony Tannous
Tony Tannous

Reputation: 14861

char atest[] = "this is a test";

Tells the compiler to allocate a char array of size 15 on stack

't', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', '\0'

If you look at atest[3] you will see s.


The next operation

atest[] = "atest is now changed"; 

Is array assignment which is not supported. Even if it was, the second string is larger than the array size, attempting to access array out of bound will invoke undefined behavior.


You may though use strcpy

strcpy(atest, "new string");

Just make sure it's not bigger than initial array size.

Upvotes: 1

Milon Mahato
Milon Mahato

Reputation: 190

You can not changed char arr by assign operator(=). You can do this.

strcpy(atest, "changed");

Upvotes: 0

Related Questions