Sliced string and char buffer are not equal

by SUBHANSHU SAHU   Last Updated September 11, 2019 19:26 PM - source

I want to extract the packet number from the received message and want to compare with originally sent packet_count and trying with following code

    char string[] = "Hello client 0000!";    
    char new[4];
    char bufNew[4];
    int i=0;
    int count=0;
    int num=0;
    int packet_counter=0;

    for (i=13;i<17;i++)
    {
        new[count] = string[i];
        count = count+1;
    }
    new[4]='\0';
    printf("Sliced no is: %s\n",new);
    sprintf(bufNew, "%04d", packet_counter);
    bufNew[4]='\0';

    printf("packet counter is: %s\n",bufNew);

    printf("String compare result: %d\n",strcmp(new,bufNew));

Although the output look same, strings are different.

Output:

Sliced no is: 0000                                                                                                            
packet counter is: 0000                                                                                                       
String compare result: 48

Please guide how to make both these strings equal.

Tags : c


Answers 1


It is likely that sprintf(bufNew, "%04d", packet_counter); overwrites the terminating 0 of new (since as others said, it is out of range). Try moving the printf("Sliced no is: %s\n",new); down below bufNew[4]='\0'; to see it for yourself.

To fix it, newand bufNew needs to be declared with size 5:

   char new[5];
   char bufNew[5];
nielsen
nielsen
September 11, 2019 19:25 PM

Related Questions