|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
如下代码:
执行后无法输出,但是把指针赋值代码屏蔽完全用数组就可以了,请教问题出在哪里?
- #include <stdio.h>
- #include<string.h>
- #include <stdlib.h>
- struct Book
- {
- char name[10];
- int num;
- }class1[2];
- int main() {
- struct Book *pa;
- pa = (struct Book *)malloc(sizeof(struct Book));
-
- int i;
- for(i=0; i<2; i++)
- {
- char str[10];
- gets(str);
- strcpy(class1[i].name,str);
- strcpy(pa->name,str);
-
- int number;
- scanf("%d",&number);
- getchar();
- pa->num = number;
- class1[i].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[i].name,class1[i].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[10];
- int num;
- }class1[2];
- int main() {
- struct Book *pa;
- pa = (struct Book *)malloc(2*sizeof(struct Book));//做了修改
-
- int i;
- for(i=0; i<2; i++)
- {
- char str[10];
- gets(str);
- strcpy(class1[i].name,str);
- strcpy(pa->name,str);
-
- int number;
- scanf("%d",&number);
- getchar();
- pa->num = number;
- class1[i].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[i].name,class1[i].num);
- pa ++;
- }
- system("pause");
- return 0;
- }
复制代码
|
|