String is longer than expected in C

前端 未结 3 932
轮回少年
轮回少年 2020-12-12 02:48

Here\'s my code

#include 
#include 

int main(){
    char pal[8] = \"ciaooaic\";
    char pal1[7] = \"ciaoaic\";
    int lenPa         


        
相关标签:
3条回答
  • 2020-12-12 03:20

    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

    0 讨论(0)
  • 2020-12-12 03:23

    1. You don't leave room for a 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 both these variables.

    0 讨论(0)
  • 2020-12-12 03:30

    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";
    
    0 讨论(0)
提交回复
热议问题