1

I have yet another question regarding pointers to strings. I want to know why this code works fine, and by that I mean that it can change the char d to the char Q.

char Name [] = "Andrew B. Mayfair";
char *pName = "Andrew B. Mayfair";
pName[2] = 'Q';
printf("%s\n", pName);

But this other lines of codes result in a segmentation fault

char *pName = "Andrew B. Mayfair";
pName[2] = 'Q';
printf("%s\n", pName);

The only difference between those codes is that on the first one the pointer pName points to the address of an already created array of characters, and the second one the pointer is created the same way as we used to create strings before (on the cs50 course I mean).

Thank you

1

The variables of type char* (string in cs50) are immutable and read only: We can not vary its content once declared. If we try to do it we will have a segfault.

An array for its part if it allows to change its content as you surely know, although we can not change its longitude.

A char* and an array are related: If you declare a char* and initialize it there is no going back But we can make a char * behave like an array at the time of initializing it, using the dynamic allocation of memory.

As an example we have the next

int main(void)
{
    char characterone = 'a';
    char charactertwo = 'b';
    char* letters = malloc(sizeof(char)*2);
    letters[0] = characterone;
    letters[1] = charactertwo;
    printf("%s\n", letters);
}

The most surprising thing is that we can change the string, for example we can do:

letters[0] = 'c';

without having a segfault:

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

    int main(void)
    {
        char characterone = 'a';
        char charactertwo = 'b';
        char* letters = malloc(sizeof(char)*2);
        letters[0] = characterone;
        letters[1] = charactertwo;
        printf("%s\n", letters);
        letters[0] = 'c';
        printf("%s\n", letters);
        free(letters);
    }

This has to do with the management of memory by the compiler and the memory area where the variables are located in each case: In the case of malloc it is located in heap, which allows us to change as we've done it.

I let you find out more about the differences between stack and heap.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .