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


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 failn");
                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]:%sn", w,p[w]);
    gc=1;
    w++;
    printf("continue y or n:");
    scanf("%c",&y_n);
    if(y_n=='n'){
        break;
    }
    getchar();
}
printf("w:%dn", w);

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

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

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


初始值 w=1 开始

循环 p 指针数组没问题

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

char *p[]={};

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

但是,它所做的是声明一个 0 大小的数组p char* s。因此,使用任何p[w]都会调用未定义的行为。它是否崩溃取决于你的运气。如果你幸运的话,它总是崩溃。

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

相关内容

最新更新