Copying string stored in pointer

Asked

Viewed 442 times

4

What is 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 waiting for the spaces to be removed from str, something close to function trim() javascript.

1 answer

4


If you want to use the memcpy() same has to copy to another place, 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);

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Or you can do inline much simpler:

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

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.