结构体指针赋值的问题
如下代码:执行后无法输出,但是把指针赋值代码屏蔽完全用数组就可以了,请教问题出在哪里?
#include <stdio.h>
#include<string.h>
#include <stdlib.h>
struct Book
{
char name;
int num;
}class1;
int main() {
struct Book *pa;
pa = (struct Book *)malloc(sizeof(struct Book));
int i;
for(i=0; i<2; i++)
{
char str;
gets(str);
strcpy(class1.name,str);
strcpy(pa->name,str);
int number;
scanf("%d",&number);
getchar();
pa->num = number;
class1.num = number;
pa ++;
}
//pa = pb;
for (i = 0;i< 2;i++)
{
//printf("name is %s,num is %d\n",pa->name,pa->num);
printf("name is %s,num is %d\n",class1.name,class1.num);
//pa ++;
}
return 0;
} 本帖最后由 小甲鱼的铁粉 于 2021-1-25 11:42 编辑
有两处错误,第一处是定义时pa = (struct Book *)malloc(sizeof(struct Book));
这里应该是两个内存空间,2 * sizeof(struct Book)
第二处是输入之后,pa++执行了两次,要让它回去之前的地址,就要 pa -= 2
正确代码如下
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include <stdio.h>
#include<string.h>
#include <stdlib.h>
struct Book
{
char name;
int num;
}class1;
int main() {
struct Book *pa;
pa = (struct Book *)malloc(2*sizeof(struct Book));//做了修改
int i;
for(i=0; i<2; i++)
{
char str;
gets(str);
strcpy(class1.name,str);
strcpy(pa->name,str);
int number;
scanf("%d",&number);
getchar();
pa->num = number;
class1.num = number;
pa ++;
}
pa -= 2;//做了修改
//pa = pb;
for (i = 0;i< 2;i++)
{
printf("name is %s,num is %d\n",pa->name,pa->num);
printf("name is %s,num is %d\n",class1.name,class1.num);
pa ++;
}
system("pause");
return 0;
} 小甲鱼的铁粉 发表于 2021-1-25 11:41
有两处错误,第一处是定义时
这里应该是两个内存空间,2 * sizeof(struct Book)
第二处是输入之后,pa++ ...
感谢指点,追加2个问题:
1、这段代码我放在main函数外面定义就报错了
struct Book *pa;
pa = (struct Book *)malloc(2*sizeof(struct Book));
2、这样定义也报错
struct Book
{
char name;
int num;
}class1,*pa=&class1;
初学基础知识不扎实,请指点敏捷 dysow 发表于 2021-1-25 11:56
感谢指点,追加2个问题:
1、这段代码我放在main函数外面定义就报错了
放在main函数外面就是全局变量,定义时就要初始化,分配好内存空间
struct Book
{
char name;
int num;
}class1;
struct Book *pa = (struct Book *)malloc(2*sizeof(struct Book));
int main() {
//省略
}
页:
[1]