1

I'm trying to manipulate a string by removing the first character or word before a space, and keeping the rest of the sentence.

For example:

char *sentence = {"I am home"};

should become: "am home"

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

int main(int argc, char** argv) {

    char *sentence = {"I am home"};  
    int space_cnt = 0;
    char *p = sentence;
    char *copy;

    printf("%s\n ", sentence);

        for (int k=0; k<strlen(sentence); k++) {
            if (space_cnt = 0 && ((p=strchr(sentence, ' ')) != NULL)) {
                space_cnt = 1;
            }
            else if (space_cnt = 1) {
                *copy++ = *p;
            }  
        }
    printf("COPY: %s\n", copy);

    return (EXIT_SUCCESS);

}

Current output:

I am home
COPY: 2�
2
  • 2
    You never allocated space for copy! Commented Dec 19, 2018 at 17:46
  • It is uninitialized, and you are copying data to an invalid location. Commented Dec 19, 2018 at 17:46

2 Answers 2

1

As noted in the comments, you never allocated copy, so you're essentially writing to unallocated space, which will produce an undefined behavior (e..g, on my machine, this code just segfaults).

In fact, you don't even need to copy the string. You can just have copy point to the first character after the space:

char *copy = strchr(sentence, ' ');
if (copy != NULL) {
        copy++;
        printf("COPY %s\n", copy);
}
1

Since a string is just a pointer to the first element in an array of char terminated by a NULL, you can use pointer arithmetic to get the string after the first word:

char mystring[100] = "Not everybody is going to like this";
char *pstring = mystring;
while(*pstring && *pstring != ' ') 
    pstring++;

puts(pstring);

Output:

 everybody is going to like this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.