首页 > C 指针数组下标问题,无法从 0开始

C 指针数组下标问题,无法从 0开始

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

int main(void){
    char *p[]={};
    char *temp=NULL;
    int end=0;
    char y_n=0;
    int w=0;//这里 设为0 时 获取 0这个指示元素时出错,设为1时 没有问题

    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;
    }
    /*test*/

请看截图:

当循环 运行到 获取 下标为 0 时的数据时 出现:Segmentation fault (core dumped) 段失败

当上面 定义的 int w=1 初始为 1 时 没有问题 下图是 w=1 时的结果

求教这个是什么原因 。


char *p[]={};
// 等同于 char *p[0];

在p指向一块内存之前,没有意义。

请参考: http://stackoverflow.com/questions/4690718/zero-length-arrays


我在fedora中出现的也是segment fault,但具体情况不相同。
内存中数据被破坏了,会出现各种诡异问题。

我把这一行

char *p[]={};

改为

char *p[10]={0};

之后,就没有这种问题了。
不明白char *p[]={};是什么写法,也没有搜索到,请教一下。


看了楼主的回复后修改一下答案:
应该是因为没有给存放char*的数组(可能叫法不准确)动态分配内存导致的问题。
进行如下修改就行了。
1.

char *p[]={};

改为

char** p = (char**)malloc(sizeof(char*));

2.

if(gc==1){
    p[w]=(char *)calloc(gc,sizeof(char));
    strcat(p[w],(char *)&end);
}

添加两行

if(gc==1){
    if (w != 0)
        p = (char**)realloc(p, (w + 1) * sizeof(char*));
    p[w]=(char *)calloc(gc,sizeof(char));
    strcat(p[w],(char *)&end);
}  

3.最后再释放为二重指针p申请的内存


char *p[]={} 一点线索, it is a GNU extension (also accepted by clang), hence gcc accepts the code.

【热门文章】
【热门文章】