![]() |
pointers strings, and strcat()
okay, i'm new to C and going crazy trying to understand this little problem.
in the code below, example A doesn't work, while B does. why is this so? i thought that declaring strings by "char *blah" and "char blah[]" would essentially be the same since arrays are just pointers anyway. am i wrong? the reason i ask this is because i'm writing a function that needs to use strings which aren't initialized with a value and hence need to have the array size automatically known ("char *blah;" works for this while "char blah[];" gives an array size unknown error). after all this, i then want the strings to be passed to strcat() for concatenation. i really hope someone can help here.. thanks. :
// EXAMPLE A |
Pointers points to an address of a variable, thus example A will not work because its 1985 and toyota is not an address.
However, example B works because you are declaring a char string to yr[] and car[]. Both 1985 and toyota in this example fills the array. Arrays are different from pointers, for yr[], yr works like a pointer but it only points to the address of the first element in the string. |
Arrays are just pointers in disguise
*(ara+2) is the same thing as ara[2] Example A didn't work because *yr didn't have enough space to hold *car |
>>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. |
| All times are GMT -5. The time now is 9:29 PM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC