I have a question about strings that hopefully someone can help with. I realise that doing something like:
char* word = malloc(4);
word = "THE";
is not really correct (as word is really a pointer to the first element as I understand it) and so we are trying to assign a character string to a pointer. However, in code in partially works and I would like to know what is going on. Below is some code to illustrate what I mean (with the standard way of writing one character at a time to the array as a comparison).
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char* word = malloc(4);
word[0] = 'T';
word[1] = 'H';
word[2] = 'E';
word[3] = '\0';
// printing out where string is stored and the string
printf("POINTER: %p\n", word);
printf("STRING: %s\n", word);
/*
* altering an element and reprinting. The string prints out
* altered and memory location prints out unaltered as expected
* in my output
*/
word[0] = '!';
printf("POINTER: %p\n", word);
printf("STRING: %s\n", word);
/*
* trying the dodgy way. In my output the pointer is altered and
* the string prints out fine. Why?
*/
word = "CAT";
printf("POINTER: %p\n", word);
printf("STRING: %s\n", word);
/*
* it only partially works though as altering a single element
* leads to a segmentation fault
*/
word[0] = '!';
printf("POINTER: %p\n", word);
printf("STRING: %s\n", word);
free(word);
}
So clearly a string is being stored somewhere but in a different location from what malloc() gave us and then after we cannot alter elements (we get a segmentation fault) only read them. If anyone can explain to me what exactly is happening I would be very appreciative!