Here's my code
#include <stdio.h>
#include <string.h>
int main(){
char pal[8] = "ciaooaic";
char pal1[7] = "ciaoaic";
int lenPal = strlen(pal);
int lenPal1 = strlen(pal1);
printf("strlen('%s'): %d\n", pal, lenPal);
printf("strlen('%s'): %d\n", pal1, lenPal1);
return 0;
}
The problem is that when I run this code the output is:
strlen('ciaooaicP@'): 11
strlen('ciaoaic'): 7
The first string has also another non-printable char between P and @. I'm a noob, so maybe I missed something obvious. Can someone help me?
edit:
just give one extra space like char pal[9] = "ciaooaic"; char pal1[8] = "ciaoaic";
It works, but why? I understand that there should be a space for \0, but "ciaoaic" works without it...
char pal[9] = "ciaooaic"; char pal1[8] = "ciaoaic";char pal[] = "ciaooaic";the compiler will include the null-terminator at the end (note:'\0'and0are equivalent). When you specify a size e.g.pal[8], you limit the size of the array to just that size. If you happen to fill them all up with characters and leave no space for a null, the compiler is happy because it trusts you know what you meant. If by happenstance, the next character followingchar pal[8] = "ciaooaic";in memory is a0, then you accidentally have a null-terminates string. Don't count on that regularly happening...palnorpal1is a string as defined by C11 §7.1.1 ¶1: A string is a contiguous sequence of characters terminated by and including the first null character. The term multibyte string is sometimes used instead to emphasize special processing given to multibyte characters contained in the string or to avoid confusion with a wide string. A pointer to a string is a pointer to its initial (lowest addressed) character. The length of a string is the number of bytes preceding the null character and the value of a string is the sequence of the values of the contained characters, in order.