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 大小的 p
的 char*
数组。因此,使用任何 p[w]
都会调用未定义的行为。能不能崩溃就看你的运气了。如果你幸运的话,它总是会崩溃。
您需要声明具有所需大小的p
。如果您不知道需要多少个元素,请将其设为 char**
并对其进行 malloc
/realloc
。
关于c - C指针数组下标,不能从0开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17259833/