简体   繁体   中英

How to understand strings with pointers

I have been studying the C language for the last few months. I'm using a book and I have this exercise:

char vector[N_STRINGS][20] = {"ola", "antonio", "susana"};
char (*ptr)[20] = vector;
char *p;

while(ptr-vector<N_STRINGS)
{
    p = *ptr;
    while(*p)
        putchar(*p++);
    putchar('\n');
    ptr++;
}

I understand everything expect the while(*p) ! I can't figure out what the while(*p) is doing.

The variable p in your code is defined as a pointer to a char . The get the actual char value that p points to, you need to dereference the pointer, using the * operator.

So, the expression in your while loop, *p evaluates - at the beginning of each loop - to the char variable that p is currently pointing to. Inside the loop, the putchar call also uses this dereference operator but then increments the pointer's value so, after sending that character to the output, the pointer is incremented (the ++ operator) and it then points to the next character in the string.

Conventionally (in fact, virtually always), character strings in C are NUL -terminated, meaning that the end of the string is signalled by having a character with the value of zero at the end of the string.

When the while loop in your code reaches this NUL terminator, the value of the expression *p will thus be ZERO. And, as ZERO is equivalent to a logical "false" in C (any non-zero value is considered "true"), the while loop will end.

Feel free to ask for further clarification and/or explanation.

From the C Standard (6.8.5 Iteration statements)

4 An iteration statement causes a statement called the loop body to be executed repeatedly until the controlling expression compares equal to 0.

In this part of the program

p = *ptr;
while(*p)
//…

the pointer p points to the first character of a current string. String in C is a sequence of characters terminated by the zero character '\\0' .

So let's for example the pointer initially points to the first character of the string "ola" . The string is represented in the corresponding character array like

{ 'o', 'l', 'a', '\0' }

The condition in the loop

while(*p)

may be rewritten like

while(*p != 0 )

So the loop will be executed for all characters of the string except the last zero-terminated character and there will be outputted the first three characters of the string.

Pay attention to that (6.5.9 Equality operators)

3 The == (equal to) and != (not equal to) operators are analogous to the relational operators except for their lower precedence.108) Each of the operators yields 1 if the specified relation is true and 0 if it is false. The result has type int. For any pair of operands, exactly one of the relations is true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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