String is longer than expected in C

那年仲夏 提交于 2019-12-02 13:16:57

问题


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...


回答1:


1. You don't leave spaces for null terminator , as you pass them to strlen() ,therefore your code exhibits undefined behaviour -

char pal[8] = "ciaooaic";
char pal1[7] = "ciaoaic";

Leave a space for '\0'. Declare and initialize like this -

char pal[9] = "ciaooaic";
char pal1[8] = "ciaoaic";

2. And strlen() returns size_t not int , so write like this -

size_t lenPal = strlen(pal);
size_t lenPal1 = strlen(pal1);

and use %zu specifier to print these both variables .




回答2:


You have not kept space for the NULL terminating character \0.


Either increase the size of the array by 1

char pal[9] = "ciaooaic";
char pal1[8] = "ciaoaic";

OR

Do not specify the length at all

char pal[] = "ciaooaic";
char pal1[] = "ciaoaic";



回答3:


Both the above answers are sufficient to solve your doubts. Increase the the length of both pal and pal1 by one as there there is no space for the assignment of the null character( '\0') at the end. However there is small trick to print the non null terminated character using printf

printf("strlen('%.*s'): %d\n",8, pal, lenPal);
printf("strlen('%.*s'): %d\n",7, pal1, lenPal1);

Link for the above trick:BRILLIANT



来源:https://stackoverflow.com/questions/33707486/string-is-longer-than-expected-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!