Using gcc 4.4.3 c89:
I am just working on the following code below:
I just have some questions about dereferencing the src pointer. Which is declared in the calling function as:
char src[] = "device_id";
My confusion rests with dereferencing the src:
for(i = 0; src[i] != '\0'; i++) {
printf("src %d: [ %s ]\n", i, &src[i]);
}
src
has decayed into a pointer. So src will be pointing to the first element in the array, which will be the character d:
src -> "device_id"
So when I do this src[i]
I am dereferencing the value so it will return the character being currently pointing at. For this example when it gets to the nul it will break from the for loop.
For example i = 0
For &src[i]
am I getting the address of the character instead of the character itself?
So where src[i]
will dereference and return d, &src[i]
will return the address of d.
Because *dest[]
is an array of char pointers it is expecting an address. So here I am assigning an address of the character to the array of pointers to char.
dest[i] = &src[i];
Is there a difference to doing either this in the printf function for %s in using either &src[i]
or src[i]
:
printf("src %d: [ %s ]\n", i, &src[i]);
or
printf("src %d: [ %s ]\n", i, src[i]);
Source code:
void inc_array(char *src, size_t size)
{
/* Array of pointers */
char *dest[size];
size_t i = 0;
memset(dest, 0, size * (sizeof char*));
/* Display contents of src */
for(i = 0; src[i] != '\0'; i++) {
printf("src %d: [ %s ]\n", i, &src[i]);
}
/* copy contents to dest */
for(i = 0; i < 9; i++) {
dest[i] = &src[i];
}
/* Display the contest of dest */
for(i = 0; *dest[i] != '\0'; i++) {
printf("dest %d: [ %s ]\n", i, dest[i]);
}
}
Many thanks for any suggestions,