Home > Back-end >  Why my printf in C removes an element of array?
Why my printf in C removes an element of array?

Time:09-19

Hello guys, i have this code:

#include <stdio.h>
    int main()
    {
    int numberPosition=8;
    char senha[1000]="01000hello";
    printf("%i\n", numberPosition);
    senha[numberPosition]="";
    printf("\n%s\n", senha);
    
    return 0;
    }

When I executes my code my return is: 01000heo.

However if I delete the line "printf("%d\n", numberPosition);" my return is: 01000helo

Why printf deletes an element from my array?

CodePudding user response:

senha[numberPosition]=""; is problematic as the left side is expecting a char but the right side is a char * which is then implicitly cast to an integer. This is often an error and gcc will generate a warning. Here is the explicit cast:

senha[numberPosition]=(unsigned long) "";

This will convert the address where the string "" is stored to an integer. It happens to evaluate to 8 which is backspace \b:

./a.out | od -a
0000000   8  nl  nl   0   1   0   0   0   h   e   l  bs   o  nl
0000016

what you want, what you really, really want is:

senha[numberPosition]='\0';

which will print:

8

01000hel

You clarified you wanted the output "01000helo" and either of these produce that output for me:

#include <stdio.h>

int main() {
    int numberPosition=8;
    char senha[1000]="01000hello";
    senha[numberPosition] = 'o';
    senha[numberPosition 1] = '\0';
    printf("%s\n", senha);
}

or:

#include <stdio.h>
#include <string.h>

int main() {
    int numberPosition=8;
    char senha[1000]="01000hello";
    strcpy(senha   numberPosition, "o");
    printf("%s\n", senha);
}

It would be a good idea to add boundary checks.

Your comment below talks about removing characters which is a different problem that you initially described. You want to check out memmove() (which permit overlap of dst, src, unlike strcpy(), memcpy()).

  • Related