C指针数组下标,不能从0开始

时间:2013-06-23 10:29:06

标签: c

int main(void){
    char *p[]={};
    char *temp=NULL;
    int end=0;
    char y_n=0;
    int w=0; //pointer array subscript 
    int gc=1;

while(true){
    printf("enter content:\n");
    while((end=getchar())!='\n'){
        if(gc==1){
            p[w]=(char *)calloc(gc,sizeof(char));
            strcat(p[w],(char *)&end);
        }
        else{
            temp=(char *)realloc(p[w],gc*sizeof(char));
            if(temp==NULL){
                printf("memory fail\n");
                break;
            }
            p[w]=temp;
            /*here temp and p[w] reference same address
            so temp pointer set value is NULL break reference address
            so temp pointer not use free function.
            if temp pointer use free function,at the same time clean p[w] in memory address.
            */
            temp=NULL;
            strcat(p[w],(char *)&end);
        }
        gc++;
    }
    printf("p[%d]:%s\n", w,p[w]);
    gc=1;
    w++;

    printf("continue y or n:");
    scanf("%c",&y_n);
    if(y_n=='n'){
        break;
    }
    getchar();
}
printf("w:%d\n", w);


    /*test*/
    while((--w)>=0){
        printf("p[%d]:%s\n", w,p[w]);
        free(p[w]);
        p[w]=NULL;
   }
    return 0;
}

--------------------------------

初始值w = 0, 循环到p [w = 0]错误:分段错误(核心转储)


初始值w = 1开始

循环p指针数组没问题

为什么呢? 没有初始值指针数组,下标不能从0开始?

1 个答案:

答案 0 :(得分:4)

char *p[]={};

是无效的C,但它是一个GNU扩展(也被clang接受),因此gcc接受代码。

然而,它所做的是声明p的0大小char*数组。所以使用任何p[w]调用未定义的行为。是否崩溃取决于你的运气。如果你很幸运,它总会崩溃。

您需要声明p所需的尺寸。如果您不知道需要多少元素,请将其设为char**malloc / realloc