在动态存储器中确保一个结构体的区域,确保完成后让用户输入结构体的信息。
使用AceStriker的结构体,如果无法确保区域,则printf输出错误消息
确保领域后,让用户输入选手名和得分数,保存到结构体中
#include <stdio.h>
typedef struct {
char name[50];
int goalno;
} AceStriker;
AceStriker hattrick(AceStriker *);
int main() {
AceStriker messi = {"Lionel Messi", 5};
messi = hattrick(&messi);
printf("%s scores a hattrick! New number of goals: %d.\n", messi.name, messi.goalno);
return 0;
}
AceStriker hattrick(AceStriker *fw) {
fw->goalno += 3;
return *fw;
}
输出结果为:
Fruit data before deleting
Code: 1008, Fruit: Apple, Price: 250
Code: 1005, Fruit: Banana, Price: 160
Code: 1009, Fruit: Kiwi, Price: 98
Code: 1013, Fruit: Grape, Price: 1650
Code: 1007, Fruit: Orange, Price: 180
Code: 1002, Fruit: Pineapple, Price: 298
Code: 1004, Fruit: Kaki, Price: 230
Code: 1010, Fruit: Nashi, Price: 370
Code: 1006, Fruit: Pear, Price: 270
Code: 1001, Fruit: Strawberry, Price: 400
*** Deleting fruit with barcode 1007 ***
Fruit data after deleting
Code: 1008, Fruit: Apple, Price: 250
Code: 1005, Fruit: Banana, Price: 160
Code: 1009, Fruit: Kiwi, Price: 98
Code: 1013, Fruit: Grape, Price: 1650
Code: 1002, Fruit: Pineapple, Price: 298
Code: 1004, Fruit: Kaki, Price: 230
Code: 1010, Fruit: Nashi, Price: 370
Code: 1006, Fruit: Pear, Price: 270
Code: 1001, Fruit: Strawberry, Price: 400
你题目的解答代码如下:
#include<stdio.h>
#include<stdlib.h>
typedef struct {
char name[50];
int goalno;
} AceStriker;
AceStriker hattrick(AceStriker *);
int main() {
AceStriker messi = {"Lionel Messi", 5};
messi = hattrick(&messi);
printf("%s scores a hattrick! New number of goals: %d.\n", messi.name, messi.goalno);
return 0;
}
AceStriker hattrick(AceStriker *fw) {
fw = (AceStriker *)malloc(sizeof(AceStriker));
scanf("%s", fw->name);
scanf("%d", &fw->goalno);
return *fw;
}
如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!
http://www.cplusplus.com/reference/cstdlib/malloc/
/* malloc example: random string generator*/
#include <stdio.h> /* printf, scanf, NULL */
#include <stdlib.h> /* malloc, free, rand */
int main ()
{
int i,n;
char * buffer;
printf ("How long do you want the string? ");
scanf ("%d", &i);
buffer = (char*) malloc (i+1);
if (buffer==NULL) exit (1);
for (n=0; n<i; n++)
buffer[n]=rand()%26+'a';
buffer[i]='\0';
printf ("Random string: %s\n",buffer);
free (buffer);
return 0;
}
看一个例子。
malloc(sizeof(AceStriker))
注意 free
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char name[50];
int goalno;
} AceStriker;
AceStriker * hattrick(AceStriker*);
int main() {
AceStriker* messiP = (AceStriker*) malloc(sizeof(AceStriker));
sprintf(messiP->name, "%s", "Lionel Messi");
messiP->goalno = 5;
messiP = hattrick(messiP);
printf("%s scores a hattrick! New number of goals: %d.\n", messiP->name, messiP->goalno);
free(messiP);
return 0;
}
AceStriker * hattrick(AceStriker* fw) {
fw->goalno += 3;
return fw;
}