0

I am trying to insert a character at a specific position in the char array (char *peep) but every time I try, I get a strcpy error

Current Code

int main(){
    char *peep = malloc(256);
   
    int pos;
    char character, charToStr[2];
    charToStr[1] = '\0';

    printf("\nCharacter to insert: ");
    scanf("%c", &character);
    printf("Position to insert: ");
    scanf("%d", &pos);
    printf("\nPeep becomes\n%d:%c", pos,character);

    charToStr[0] = character;
    strcpy(peep[pos-1],charToStr);
    
    printf("this is peep: \n%d:%c",pos,peep[pos-1]);
   
}

I have tried using strncpy() to no avail and honestly tried many other things

  • 1
    strcpy expects a char pointer as its first argument, you are passing a char. – Fredrik Nov 28 '21 at 06:24
  • i want the character being passed to go in a specific spot how would i do that without that first argument being what it is? –  Nov 28 '21 at 06:26
  • 1
    `peep[pos-1] = character;`? Though not sure what you are really trying to do as the rest of `peep` will still contain garbage data. – kaylum Nov 28 '21 at 06:28
  • `printf("this is peep: \n%d:%c",pos,peep[pos]);` and why are you trying to print at index `pos` when it is index `pos-1` that is being set? The whole code really makes very little sense. – kaylum Nov 28 '21 at 06:29
  • that was a typo thanks for your 1st comment –  Nov 28 '21 at 06:41

1 Answers1

0

Look at the signature of the strcpy function:

char *strcpy(char *dest, const char *src);

As you can see, this function expects a character pointer as the destination string.

In your code however, you are passing a plain character to the function. This is because you are dereferencing the string at the index [pos-1].

Hence, you have to use the ampersand (&) operator in order to pass the adress of your destination string. Therefore, changing your strcpy call to strcpy(&peep[pos - 1], charToStr); will make your code work as intended.