What is the difference between char a[] = ?string?; and char *p = ?string?;?

前端 未结 8 1001
太阳男子
太阳男子 2020-11-22 07:43

As the heading says, What is the difference between

char a[] = ?string?; and 
char *p = ?string?;  

This question was asked to me in inter

8条回答
  •  隐瞒了意图╮
    2020-11-22 08:06

    Stack, heap, datasegment(and BSS) and text segement are the four segments of process memory. All the local variables defined will be in stack. Dynmically allocated memory using malloc and calloc will be in heap. All the global and static variables will be in data segment. Text segment will have the assembly code of the program and some constants.

    In these 4 segements, text segment is the READ ONLY segment and in the all the other three is for READ and WRITE.

    char a[] = "string"; - This statemnt will allocate memory for 7 bytes in stack(because local variable) and it will keep all the 6 characters(s, t, r, i, n, g) plus NULL character (\0) at the end.

    char *p = "string"; - This statement will allocate memory for 4 bytes(if it is 32 bit machine) in stack(because this is also a local variable) and it will hold the pointer of the constant string which value is "string". This 6 byte of constant string will be in text segment. This is a constant value. Pointer variable p just points to that string.

    Now a[0] (index can be 0 to 5) means, it will access first character of that string which is in stack. So we can do write also at this position. a[0] = 'x'. This operation is allowed because we have READ WRITE access in stack.

    But p[0] = 'x' will leads to crash, because we have only READ access to text segement. Segmentation fault will happen if we do any write on text segment.

    But you can change the value of variable p, because its local variable in stack. like below

    char *p = "string";
    printf("%s", p);
    p = "start";
    printf("%s", p);
    

    This is allowed. Here we are changing the address stored in the pointer variable p to address of the string start(again start is also a read only data in text segement). If you want to modify values present in *p means go for dynamically allocated memory.

    char *p = NULL;
    p = malloc(sizeof(char)*7);
    strcpy(p, "string");
    

    Now p[0] = 'x' operation is allowed, because now we are writing in heap.

提交回复
热议问题