dereferencing an array
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,
For
&src[i]
am I getting the address of the character instead of the character itself? So wheresrc[i]
will dereference and returnd
,&src[i]
will return the address of d.
src[i]
is equivalent to *(src + i)
, so &src[i]
is the same as &*(src + i)
, which can be reduced to src + i
. It is just performing pointer arithmetic and no dereferencing takes place.
src[i]
gives you the character in src
at index i
, and &src[i]
gives you a pointer to the i
th character in src
.
The format specifier %s wants to insert a string, so if you pass it &src[i], it will start at the i-th character of src and print until the null-terminator. You almost definitely want %c instead of %s, and src[i] instead of &src[i].
Yes, there's a difference. &src[i]
is the address of the character at src[i]
, as you correctly say. src[i]
is the character itself.
For both printing with "%s"
and assigning to a char *
object, &src[i]
is the correct formulation.
(By the way, &src[i]
can also be written as src + i
, if you like).
精彩评论