-1

I am trying to figure out a way to remove a char from a string based on an index value using pointers and not touching array notation (by which I essentially mean not using any brackets) at all. As far as I understand *letter = temp should assign what is in temp into the location of letter, but it creates a segmentation fault instead.

char *word = "blue";
int length = strlen(word);
int index = 0;

for (index; index < length; index++)
{   
    char *letter = word + index;
    char temp;
    temp = *(letter + 1);
    *letter = temp;
}
    printf("%s\n", word);

Edit: Bolded something that the answers seem to be ignoring.

Hex
  • 1
  • 1
  • 3
  • It does not let you change the string literal. try change to `char word[] = "blue";` – BLUEPIXY Sep 27 '14 at 01:09
  • *Dozens* duplicates related to this question, one well written being : [Why do I get a segmentation fault when writing to a string?](http://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-string) – WhozCraig Sep 27 '14 at 01:23
  • My solution avoids the brackets. Bluepixy would have been correct on any other question. – Michael Petch Sep 27 '14 at 01:32

2 Answers2

0

word is a pointer which is initialized to point to a string constant. The pointer word may be modified to point to another string, however if you attempt to modify the string at which word is pointing the result is undefined.

Instead you can do char word[] = "blue". Here word is an array big enough to hold a word and \0 following the word. Individual characters within the array can be changed however the address of the array will remain same.

ani627
  • 5,578
  • 8
  • 39
  • 45
0

I've put my comments in the code about what is going on

    /* normally we would do char word[] = "blue" but that isn't allowed
     * We need to put it on the heap where it can be modified but
     * we can't use array indexing [] so we can do the hack
     * below */

    /* String constants are immutable - they can't be changed
     * so consider them read only. Trying to modify one can
     * lead to undefined behavior including write fault */
    char *constWord = "blue";
    int index = 0;
    int length = strlen(constWord);

    /* Create space on the heap to hold the string + nul terminator */
    char *word = malloc(strlen(constWord + 1));

    /* Copy the string to the heap where it can be modified */
    strcpy(word, constWord);

    for (index; index < length; index++) {
        char *letter = word + index;
        char temp;
        temp = *(letter + 1);
        *letter = temp;
    }

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

    /* Cleanup */
    free(word);
}
Michael Petch
  • 46,082
  • 8
  • 107
  • 198
  • I have no problem saying that this is wrong. If you don't know why, read again your code –  Mar 25 '18 at 23:58