分配给另一个char指针后,char指针的值会发生变化

时间:2015-01-10 07:00:03

标签: c pointers

我将“arr”视为“指向char的指针”的数组。在下面的代码中将char指针从“arr”分配到“first”和“second”后,为什么地址会发生变化?

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

int main(){
        char * arr = (char *) malloc (sizeof(char *) * 2);
        char * first;
        char * second;

        ((char **)&arr)[0] = "ABCD";
        ((char **)&arr)[1] = "EFGH";

        printf("BEFORE : ((char **)&arr)[0] = %s, Address: %p \n",((char **)&arr)[0], ((char **)&arr)[0] );
        printf("BEFORE : ((char **)&arr)[1] = %s, Address: %p \n",((char **)&arr)[1], ((char **)&arr)[1] );

        first = ((char **)&arr)[0];
        second = ((char **)&arr)[1];

        printf("AFTER : ((char **)&arr)[0] = %s, Address: %p \n",((char **)&arr)[0], ((char **)&arr)[0] );
        printf("AFTER : ((char **)&arr)[1] = %s, Address: %p \n",((char **)&arr)[1], ((char **)&arr)[1] );

        printf("first = %s\n",first);
        printf("second = %s\n",second);

return 0;
}

输出

BEFORE : ((char **)&arr)[0] = ABCD, Address: 0x400708 
BEFORE : ((char **)&arr)[1] = EFGH, Address: 0x40070d 
AFTER : ((char **)&arr)[0] = ABCD, Address: 0x400708 
AFTER : ((char **)&arr)[1] = ABCD, Address: 0x400708 
first = ABCD
second = ABCD

修改

I am using gcc version 4.8.2

1 个答案:

答案 0 :(得分:4)

您的代码在以下表达式中有undefined behaviour

    ((char **)&arr)[1]

你的意思是写

    ((char **)arr)[1]

顺便说一句,如果你首先声明arr是正确的类型,那么你就不需要那些乏味且容易出错的演员:

int main() {
        char ** arr = malloc(sizeof(char *) * 2);
        char * first;
        char * second;

        arr[0] = "ABCD";
        arr[1] = "EFGH";

        printf("BEFORE : arr[0] = %s, Address: %p \n", arr[0], arr[0]);
        printf("BEFORE : arr[1] = %s, Address: %p \n", arr[1], arr[1]);

        first = arr[0];
        second = arr[1];

        printf("AFTER : arr[0] = %s, Address: %p \n", arr[0], arr[0]);
        printf("AFTER : arr[1] = %s, Address: %p \n", arr[1], arr[1]);

        printf("first = %s\n", first);
        printf("second = %s\n", second);

        free(arr);

        return 0;
}