View Single Post
Old Apr 16th, 2005, 1:23 PM   #4
Eggbert
Professional Programmer
 
Eggbert's Avatar
 
Join Date: Nov 2004
Posts: 250
Rep Power: 4 Eggbert is on a distinguished road
>>would essentially be the same since arrays are just pointers anyway
Arrays are not pointers and pointers are not arrays. An array name is converted to a pointer to the first element in many situations, so it may seem that way, but mistaking one for the other results in subtle and dangerous errors.

>>example A doesn't work, while B does. why is this so?
Actually, both are wrong. Example A attempts to modify a string literal and example B tries to copy more data into an array than the array can hold. Here are the differences.

>>char *yr="1985";
yr is a pointer to a string literal. The string literal may be placed in read-only memory, so it is effectively constant. And attempt to modify the memory that yr points to is an error.

>>char yr[]="1985";
yr is an array that was initialized with a string literal. The size of the array-because it was omitted-is determined by the length of the string literal, including the null character. So the length of yr is 5 and it was initialized with {'1','9','8','5','\0'}. Because yr resides within your address space and is not read-only, you can modify it.
Eggbert is offline   Reply With Quote