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

标签 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开始?

最佳答案

char *p[]={};

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

但是,它所做的是声明一个 0 大小的 pchar* 数组。因此,使用任何 p[w] 都会调用未定义的行为。能不能崩溃就看你的运气了。如果你幸运的话,它总是会崩溃。

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

关于c - C指针数组下标,不能从0开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17259833/

相关文章:

c - 如何使用双指针进行深拷贝?

c - 来自 strtol 的意外输出

c - 仅取消引用一次双指针?

在 C 中使用链表时控制内存

c++ - 以 24 小时格式比较 C/C++ 中的小时数

c - 在客户端和服务器接收部分动态分配足够的内存

c - 如何使堆栈在 osx 上可执行?

c - 服务和应用程序之间的命名管道通信

c - 如何从\n 分隔文件中读取字符串

c - 如何调试预处理器宏