使用数组的分段错误
问题描述:
如果我按以下方式编写,会发生分段错误。但如果我写printf(messages[0])
或printf(messages[1])
,我没有错误。为什么?我想用“for”打印所有数组成员。使用数组的分段错误
void givetag(char *array[]); //define function
int main()
{
char* messages[3];
givetag(messages); //sub function
int i;
for(i=0;i<3;i++)
{
printf(messages[i]);
}
}
void givetag(char *array[])
{
int i;
for(i=0; i<3; i++)
{
array[i]= (char*) malloc(10);
scanf("%s", array[i]);
}
}
答
#include <stdio.h>
#include <stdlib.h>
void
givetag(char *array[])
{
int i;
for(i=0; i<3; i++){
array[i]= (char*) malloc(100);
scanf("%s", array[i]);
}
}
int main()
{
char* messages[3];
givetag(messages); //sub function
int i;
for(i=0;i<3;i++) {
printf(messages[i]);
}
printf("\n");
return 0;
}
,你在放出来的图片中看到,你必须添加的malloc大小(我改变代码)。
你正在编译为C或C++吗?请不要标记两者。 – aschepler
无法重现。 http://coliru.stacked-crooked.com/a/3a956a1207bc2bc3 – aschepler
向我们显示您的输入。 – BLUEPIXY