|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
使用的软件是vs,Visual Studio 2019,语言是c。
很典型的作业,建立一个结构体student,包含年龄age和姓名name。建立学生s1和指向s1的*p[0]。
源代码如下:
#include <stdio.h>
#include <iostream>
struct STU {
int age;
char name[20];
};
struct STU s1;
struct STU* p[1] = { &s1 };
void input() {
int j = 0;
char c;
scanf_s("%d",(*p[0]).age,10); //输入年龄
getchar();
for (j = 0, c = 0; (c = getchar()) != '\n'; j++) { //输入姓名
(*p[0]).name[j] = c;
}
(*p[0]).name[j] = '\n';
}
int main() {
int i = 0;
char h;
input();
printf("%d\n", (*p[0]).age);
for (i = 0, h = 0; ( h = (*p[0]).name[i] ); i++){
putchar(h);
}
system("pause");
return 0;
}
想法就是在自定义的input函数里改变指针从而改变结构体里的数据。“重新生成解决方案”的时候没有报错,不过有几个警告,看不太懂,请大佬教教:
然后我抱着侥幸的心理想着警告也不影响运行,结果就发现运行不了:
CSDN逛了一下听说是“由于数据超出内存所致”或者“文件调试的时候关闭导致损坏”,但我还是没找到究竟是哪里出问题了。。。
请各位大佬救救孩子
本帖最后由 jackz007 于 2022-9-18 13:19 编辑
- #include <stdio.h>
- #include <stdlib.h>
- struct STU {
- int age ;
- char name[20] ;
- struct STU * next ;
- } ;
- struct STU * input(struct STU * x)
- {
- struct STU * p ;
- if((p = (struct STU *) malloc(sizeof(struct STU)))) {
- printf("input name please : ") ;
- scanf_s("%s", & p -> name , 20) ;
- printf("input age please : ") ;
- scanf_s("%d", & p -> age) ;
- p -> next = x ;
- } else {
- fprintf(stderr , "failure of malloc():\n") ;
- }
- return p ;
- }
- void disp(struct STU * x)
- {
- for(; x ; x = x -> next) printf("name : %20s , age : %2d\n" , x -> name , x -> age) ;
- }
- void destroy(struct STU * x)
- {
- struct STU * p ;
- for(; x ;) {
- p = x ;
- x = p -> next ;
- free(p) ;
- }
- }
- int main(void)
- {
- struct STU * L = NULL ;
- int i , n ;
- printf("input the number of people please : ") ;
- scanf_s("%d" , & n) ;
- for(i = 0 ; i < n ; i ++) L = input(L) ;
- disp(L) ;
- destroy(L) ;
- system("pause") ;
- }
复制代码
编译、运行实况:
- D:\[00.Exerciese.2022]\C>g++ -o x x.c
- D:\[00.Exerciese.2022]\C>x
- input the number of people please : 5
- input name please : abc
- input age please : 18
- input name please : def
- input age please : 19
- input name please : efg
- input age please : 20
- input name please : fgh
- input age please : 21
- input name please : ghi
- input age please : 22
- name : ghi , age : 22
- name : fgh , age : 21
- name : efg , age : 20
- name : def , age : 19
- name : abc , age : 18
- 请按任意键继续. . .
- D:\[00.Exerciese.2022]\C>
复制代码
|
|