Copying string stored in pointer

2

What's wrong?

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

int main(void) {
    char *str= "   teste";

    int j = 0;
    while(str[j] == ' ') j++;
    memcpy(str, &str[j], strlen(&str[j])+1);

    printf("%s", str);

    return 0;
}

When I execute the code I only get as output:

Falha de segmentação (imagem do núcleo gravada)

While I expected spaces to be removed from str , something close to the trim() function of javascript.

    
asked by anonymous 30.04.2016 / 16:49

1 answer

2

If you want to use memcpy() even have to copy to another place, you can not do on top of the same string :

char *str = "   teste";
int j = 0;
while (str[j] == ' ') j++;
int size = strlen(str) - j + 1;
char *result = malloc(size);
memcpy(result, str + j,  size);
printf("%s", result);

See running on ideone .

Or you can do inline in a much simpler way:

char *str = "   teste";
while (*str++ == ' ');
str--;
printf("%s", str);

See running on ideone .

    
30.04.2016 / 17:42