首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

c语言结构体和指针的有关问题

2013-11-11 
c语言结构体和指针的问题#includestdio.hstruct inf{int numchar name[12]}int main(){FILE *fpstru

c语言结构体和指针的问题
#include<stdio.h>
struct inf
{
int num;
char name[12];
};
int main()
{
FILE *fp;
struct inf *p;
scanf("%d",&p->num);
scanf("%s",&p->name);
fp=fopen("test.txt","wb");
fwrite(p,sizeof(struct inf),1,fp);
printf("%d",p->num);
printf("%s",p->name);
fclose(fp);
return 0;
}
提示说p未定义,为什么啊? c语言 结构体 指针
[解决办法]
struct inf *p; 你这个指针指向谁呢?你没有实际定义
[解决办法]
没有分配内存,非法访问, 看看 已经帮你修改过来了


#include<stdio.h>
#include<stdlib.h> 
struct inf
{
int num;
char name[12];
};

int main()
{
FILE *fp;
struct inf *p = (struct inf *)malloc(sizeof(struct inf));
scanf("%d",&p->num);
scanf(" %s",p->name);
fp=fopen("test.txt","wb");
 if (fp == NULL)
  {
      printf("open the file failed!\n");
    return 0;
     }
fwrite(p,sizeof(struct inf),1,fp);// 检查下返回值 

printf("%d \n",p->num);
printf("%s\n",p->name);
fclose(fp);
return 0;
}

热点排行