简体   繁体   English

我很困惑

[英]I am confused in strings

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 . 它表示数组arr的第一个元素的地址是&arr[0] ,它也可以写成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打印它

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? 问题更新:现在在下面的例子中*W指向单词,这意味着它指向字符串word的第一个地址对吗? How does this access complete string word ? 这如何访问完整的字符串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]; 
}

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". 转换说明符%s说:“给我一个字符的地址。我将打印该字符,然后查看下一个更高的地址并打印字符,依此类推,直到我正在查看的地址中的字符是零“。 So string is indeed the address of a character, but printf knows what to do with it. 所以string确实是一个字符的地址,但printf知道如何处理它。

char string[0] = "ilovejapan"; isn't a valid declaration. 不是有效的声明。 Maybe you meant to leave the 0 out? 也许你打算留下0

Anyway, the %s format specifier is intended to match up with a pointer to a string, which in your case is just fine. 无论如何, %s格式说明符旨在与指向字符串的指针匹配,在您的情况下就可以了。 It prints characters from that address up until the terminating null character. 它会从该地址打印字符,直到终止空字符。

When you pass string in printf("%s", string); printf("%s", string);传递stringprintf("%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. ,你告诉printf你想打印一个字符串,你告诉函数字符串中第一个字符的地址。 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. 使用其地址, printf可以确定该地址存储的字符,并增加第一个字符的地址以获取第二个字符的地址,并打印该字符,依此类推。 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 ). 当它找到一个字符(不是该字符的地址,但实际字符本身)时,它会停止打印,其值为'\\0' (“零”字符,或由数字0表示的字符)。 If that makes any sense. 如果那有意义的话。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM