Code Bye

结构体包含结构体指针的问题

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BUFFER_SIZE 80
#define DATA_SIZE 1024
#define MAX_TLTLENUM 10
int load_data ();
typedef char STRING[BUFFER_SIZE];
typedef struct {
int type; //type用整数表示,1为string类型,-1为number类型,0为未定义。
STRING title;
} FIELD,*PFIELD;
struct library {
int cols;
int rows;
STRING name;
PFIELD title[MAX_TLTLENUM];
char *data[DATA_SIZE];
} context;
int
main(void)
{
load_data();
printf(“%s,%d,%d”,context.name,context.rows,context.cols);
getchar();
}
int load_data ()
{
char ch[BUFFER_SIZE];
int flag,count;
char *p;
/*打开配置文件*/
FILE*fp;
if ((fp = fopen (“配置文件.txt”,”r”)) == NULL)
{
printf(“Can”t open the file\n”);
return 0;
}
/*载入配置到结构中*/
fgets(ch,10,fp);
if (strcmp(ch,”[name]”) != 1){
printf(“配置文件有误。”);
exit(0);
}
fgets(context.name,10,fp);
fgets(ch,10,fp);
if (strcmp(ch,”[size]”) != 1){
printf(“配置文件有误。”);
exit(0);
}
fgets(ch,10,fp);
context.rows = atof(ch);
context.cols = atof(ch+2);
fgets(ch,10,fp);
if (strcmp(ch,”[field]”) != 1){
printf(“配置文件有误。”);
exit(0);
}
for (fgets(ch,20,fp),count = 0,flag = 0;count<3;count++){
p = strpbrk(ch,”::”);
printf(“%s”,p+2);
if (strcmp(p+2,”string”) == 1)
context.title[count]->type = 1;
else if (strcmp(p+2,”number”) == 1)
context.title[count]->type = -1;
else printf(“wrong in type of field”);
while(flag = 0,strcmp(p,ch+flag) != 1)
flag++;
strncpy(context.title[count]->title,ch,flag);
fgets(ch,20,fp);
printf(“%d”,context.title[count]->type);
}
return 1;
}
以上源代码,能够经过调试返回”string“,然后发生错误
通用的信息管理系统.exe 中的 0x002a1748 处有未经处理的异常: 0xC0000005: 写入位置 0x00000000 时发生访问冲突
指向红色那段代码。问一下是什么问题?
解决方案

10

PFIELD title[MAX_TLTLENUM];指针数组titile初始化了没有?
没有初始化直接调用context.title[count]->type = 1;

60

你这样写的话(PFIELD title[MAX_TLTLENUM];)定义出来的是一个指针数组
你需要为每一个元素(即指针)都分配空间,否则的话指针指向的是一块未知的区域,你尝试写入的话会报异常

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明结构体包含结构体指针的问题