c语言 数组操作异常

main函数接收子函数处理的数组,遍历数组时异常
示例代码:
#include
#include
#include
voiddemo(char*list[])
{
inti;
charname[10];
for(i=0;i<10;i++){
sprintf(name,"root%d",i);
list[i]=name;
printf("%d=>%s\n",i,list[i]);
}
}
voidmain()
{
char**list;
inti,len=10;
//可变数组
list=(char**)malloc(sizeof(char));
demo(list);
printf("\n");
for(i=0;iprintf("%d=>%s\n",i,list[i]);
}
}
慕容3067478
浏览 522回答 2
2回答

烙印99

list=(char**)malloc(sizeof(char));listonlypointtoamemoryareawhosesizeisonechar,that'sfarmorefromenough.ItwillcausesegmentfaultThesolutionistoallocateenoughforlist:constintN=200;//Nisthemaximuxlengthofeachstringchar**list=malloc(len*sizeof(char*));//Allocaterowpointersfor(i=0;i
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript