tangger
tangger

Reputation: 31

Some questions about strings

I encountered a problem. In the following code, I expected the length of the string p to be 3, but the actual length is 6. This is the first place I wonder. Then, when I debug myself, the length of the debugged p is in line with the expected result. This makes me feel very puzzled. I do n’t know why the length of p is 6, and why the length becomes 3 when debugging. . Can someone answer this question?

#include <cstring>
#include <cstdio>

int main()
{
    char p[]={'a','b','c'}, q[10] = {'a','b','c'};
    printf("%p  %p\n",&q,&p);
    printf("%d  %d\n",strlen(q),strlen(p));
    return 0;
}

pic-1 pic-2

Upvotes: 0

Views: 64

Answers (3)

Sourav Ghosh
Sourav Ghosh

Reputation: 134356

The problem is, p is not a null-terminated character array, so it cant be used as a string. Using this as argument to function calls which expect a string, will cause undefined behaviour (UB).

The output of a program containing UB cannot be justified in any manner.

To add some more context, q is null-terminated, as per the rule of initializer list having less argument than the size of aggregate, the remaining members get initialized as if they had static storage, so in case of char type, they get initialized with 0 (which is the null terminator needed for a string). So, using q as a string is fine.

Solution:

You can either

  • mention a dimension more than that of the elements of the initializer list
  • put a null value as the last element n the initializer list {'a','b','c', '\0'}
  • use a string (instead of initializer list) to initialize the array, like "abc", which will include the null terminator in the array.

Upvotes: 3

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

p is not null-terminated; strlen keeps counting until it sees a null (or your program is aborted because you access memory that is not yours).

Note that q is initialized, and any array elements not provided in the initializer are set to null.

Upvotes: 1

Aplet123
Aplet123

Reputation: 35540

In C, strings have to end with a null byte, and that's how strlen finds their length. Declare your strings like this and the length will show up properly:

char p[]={'a','b','c', '\0'}, q[10] = {'a','b','c', '\0'};

Upvotes: 2

Related Questions