很弱弱的指针问题
这几天刚学到struct和指针,想做一下小练习,但碰到这样的问题弄了半天也没有弄明白这是怎么回事,高手们帮忙解答一下啊,请看======这里
#include<stdio.h>指针 struct
#include<stdlib.h>
#include<string.h>
struct Dictionary
{
char *word;
int count;
};
int InitStruct(struct Dictionary **dic);
int main()
{
char buffer[20] ={'\0'};
struct Dictionary *dic=NULL;
InitStruct(&dic);
int n = 0;
if(n==0)
{
printf("%s \r\n",(dic+N)->word);// 这里把0<=N<29都能正常输出 =============
}
else
{// 这里连续输出为什么会报错呢? ==============
printf("%s \r\n",(dic+9)->word);
printf("%s \r\n",(dic+15)->word);
printf("%s \r\n",(dic+15)->word);
printf("%s \r\n",(dic+15)->word);
printf("%s \r\n",(dic+15)->word);
}
gets(buffer);
return 0;
}
//初始化struct
int InitStruct(struct Dictionary **dic)
{
struct Dictionary dicTmp[]=
{
{"1",0},
{"2",0},
{"3",0},
{"4",0},
{"5",0},
{"6",0},
{"7",0},
{"8",0},
{"9",0},
{"10",0},
{"11",0},
{"12",0},
{"13",0},
{"14",0},
{"15",0},
{"16",0},
{"17",0},
{"18",0},
{"19",0},
{"20",0},
{"21",0},
{"22",0},
{"23",0},
{"24",0},
{"25",0},
{"26",0},
{"27",0},
{"28",0},
{"29",0},
{"30",0}
};
*dic = dicTmp;
return 0;
}
[解决办法]
先不考虑输出结果的对错,代码里面InitStruct函数的做法本身就是错误的。dicTemp的内存是在栈上分配的,所以InitStruct函数返回之后,这片内存就会被销毁。结果正确只是偶然情况。
正确的做法是,使用malloc来分配内存,或者使用全局变量。
[解决办法]
注意需要分配内存:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct Dictionary
{
char *word;
int count;
};
int InitStruct(struct Dictionary **dic);
int main()
{
char buffer[20] ={'\0'};
struct Dictionary *dic=(struct Dictionary *)malloc(sizeof(struct Dictionary) * 60);
InitStruct(&dic);
int n = 2;
if(n==0)
{
printf("%s \r\n",(dic+n)->word);// 这里把0<=N<29都能正常输出 =============
}
else
{// 这里连续输出为什么会报错呢? ==============
printf("%s \r\n",(dic+9)->word);
printf("%s \r\n",(dic+15)->word);
printf("%s \r\n",(dic+15)->word);
printf("%s \r\n",(dic+15)->word);
printf("%s \r\n",(dic+15)->word);
}
gets(buffer);
return 0;
}
//初始化struct
int InitStruct(struct Dictionary **dic)
{
struct Dictionary dicTmp[]=
{
{"1",0},
{"2",0},
{"3",0},
{"4",0},
{"5",0},
{"6",0},
{"7",0},
{"8",0},
{"9",0},
{"10",0},
{"11",0},
{"12",0},
{"13",0},
{"14",0},
{"15",0},
{"16",0},
{"17",0},
{"18",0},
{"19",0},
{"20",0},
{"21",0},
{"22",0},
{"23",0},
{"24",0},
{"25",0},
{"26",0},
{"27",0},
{"28",0},
{"29",0},
{"30",0}
};
//*dic = dicTmp;
memcpy(*dic, dicTmp, sizeof(dicTmp));
return 0;
}
[解决办法]
//改成这样把,加个关键字 static
static struct Dictionary dicTmp[]=
{
{"1",0},
{"2",0},
{"3",0},
{"4",0},
{"5",0},
{"6",0},
{"7",0},
{"8",0},
{"9",0},
{"10",0},
{"11",0},
{"12",0},
{"13",0},
{"14",0},
{"15",0},
{"16",0},
{"17",0},
{"18",0},
{"19",0},
{"20",0},
{"21",0},
{"22",0},
{"23",0},
{"24",0},
{"25",0},
{"26",0},
{"27",0},
{"28",0},
{"29",0},
{"30",0}
};
看看c primer plus 里面的 指针数组这块知识吧!
[解决办法]
dicTemp的内存是在栈上分配的,所以InitStruct函数返回之后,这片内存就会被销毁
[解决办法]
static struct Dictionary dicTmp[]=