Louis93
Louis93

Reputation: 3921

What is the recommended procedure for initializing char arrays?

char label[10] = "Me" works, and to change the value of label, I'd have to do something like:

char * temp = "Not Me";
strcpy(label,temp);

My question is why is this invalid?

char label[] = "Me";
label = "Not me";

Upvotes: 1

Views: 172

Answers (3)

T.E.D.
T.E.D.

Reputation: 44814

In C, an array label is essentially the same as a pointer label, except that the array automatically gets some memory allocated behind it when defined.

Otherwise, array labels and pointer labels are treated as the same thing. So even if you declared label as an array, if you operate directly on label (without braces after it), you are treating it as a pointer (that happens to point to the first array element). Likewise, if you declare label as a pointer, but operate on label[x], you are operating on the xth data item past the place label points to (aka: *(label + x)).

Your first instinct may be that looks crazy unsafe. You'd be right. The language was designed back in the late 60's and early 70's when making compilers easy to implement on the tiny machines of the day was much more important than how error-prone the langauge was.

Upvotes: -2

Porkbutts
Porkbutts

Reputation: 964

The reason label="Not Me" will not work, is because the type of label is a char *. You defined it as an array, and arrays and pointers are semantically equivalent. A pointer is an address, basically an int so it does not make sense to assign something like "Not Me" to something that has a type of pointer.

What you need to do is dereference the pointer and assign a value to the location that is pointed to. Since the type is char * you would need to dereference each location and assign a character to each location.

E.g.

label[0] = 'N';
label[1] = 'o';
...

Or use some for loop equivalent.

Upvotes: 0

Ed Swangren
Ed Swangren

Reputation: 124790

Because arrays are not assignable. You can create them, you can change their content, but the array itself cannot be modified to refer to a new chunk of memory.

Upvotes: 5

Related Questions