array and pointers

What is the difference between a
char name[5]="abc";
char *name="abc";

is there any difference between a integer pointer and char pointer how elements and there addresses are accessed in both the cases
First of all, I'm no authority on the subject of pointers and arrays and their various differences, but I read that article the other day. I understood it, but it didn't answer the question that I had - the very same one that was asked here. The reason it didn't answer the question is because
char *name = "abc";
is not the same as
1
2
char *name = new name[4];
name = strcpy(name, "abc");


char name[5] allocates an array that holds up to 5 characters. You only store 4 in your example ("abc" and the null terminator), but it creates 5 elements for storage anyway. Arrays are naturally modifiable, though you can't point an array at a new address.

char *name creates only a pointer. Effectively, that string literal may be created in a read-only memory location, meaning that you cannot modify it (behavior is undefined). You can point this pointer at a new location, such as the beginning of an array.

As for the difference between an integer pointer and a character pointer, they are different. They are accessed the same way, but the addresses of are different. The address of an element in an array is calculated like this (remember that arrays can also be used like pointers somewhat):
address = (offset * sizeof(type)) + base

For example, suppose that an integer is 4 bytes in size (sizeof(int) = 4) and you wanted to access the 20th element in an array. Here is how it would be done:
address of int_array[20] = (20 * sizeof(int)) + int_array = (20 * 4) + int_array = int_array + 80

Of course, int_array is only a pointer to the beginning of the array, so it is the "base address".

In contrast, a character pointer (or character array) only takes up 1 byte:
address of char_array[20] = (20 * sizeof(char)) + char_array = (20 * 1) + char_array = char_array + 20

Quite a bit of difference? I think so! ^_^


To summarize:
char[] creates an array of characters; the address is constant, but the elements are not modifiable

char* creates a character pointer; the address is modifiable, but the contents may not be modifiable (in other words, don't modify the strings!)

char* != int* because the size of the data types is not always the same.


I hope this helps!
Last edited on
Topic archived. No new replies allowed.