Reputation:
I am studying pointers right now. So, arrays are simultaneously studied with that. It says that address of first of element of array arr
is &arr[0]
which can also be written as arr
.
But as i know that string is an array of characters so if have a string:
char string[] = "ilovejapan";
and then print it using printf
printf("%s", string);
shouldn't it be just printing the first address? Really confused Now.
Question updated: Now in the example below *W
points to word that means it pointers to the first address of the string word
right? How does this access complete string word
?
int getword(char *word, int lim)
{
int c, getch(void);
void ungetch(int);
char *W = word;
while (isspace(c = getch()))
;
if (c != EOF)
*W++ = c;
if (lisalpha(c)) {
*W = '\0';
return c;
}
for ( ; --lim > 0; W++)
if ( lisalnum(*W = getch())) {
ungetch ( *W) ;
break;
}
*W = '\0';
return word[O];
}
Upvotes: 2
Views: 88
Reputation: 10107
When you pass string
in printf("%s", string);
, you are telling printf
you want to print a string and you are telling the function the address of the first character in the string. Using its address, printf
can figure out what character is stored at that address, and increments the address of the first character to get the address of the second character, and prints that character, and so on. It stops printing when it finds a character (not that character's address, but the actual character itself) whose value is '\0'
(the "zero" character, or the character represented by the number 0
). If that makes any sense.
Upvotes: 1
Reputation: 477640
The conversion specifier %s
says, "Give me the address of a character. I will print that character, and then look at the next higher address and print that character, and so forth, until the character at the address I'm looking at is zero". So string
is indeed the address of a character, but printf
knows what to do with it.
Upvotes: 7
Reputation: 225242
char string[0] = "ilovejapan";
isn't a valid declaration. Maybe you meant to leave the 0
out?
Anyway, the %s
format specifier is intended to match up with a pointer to a string, which in your case is just fine. It prints characters from that address up until the terminating null character.
Upvotes: 2