此代码是关于 C 中的“结构”..
我创建了一个带有属性名称和年龄的 struct spieler.. 通过使用 for 循环,我让用户创建结构对象。 它们被命名为 sp[i] --> sp1、sp2 等。
问题是对象被创建了。但我只能在 for 循环中使用它们。 如果我想在main函数中获取“sp1.name”的值,这是行不通的。 怎么解决呢?
struct spieler{
char name[20];
int age;
};
void erzeuge();
int main() {
int anzahl = 2;
printf("Anzahl Spielern: ");
scanf("%d",&anzahl);
erzeuge(anzahl);
printf("Es sind %d Spielern",anzahl);
/*for(i;i<anzahl;i++){
printf("%d.%s",i, sp[i].name);
}*/
getchar();
}
void erzeuge(int anzahl){
int i=0;
for(i;i<anzahl;i++){
struct spieler sp[i];
printf("Struct fuer Spieler_%d wurde erzeugt\n", i);
getchar();
printf("Name: ");
scanf("%s",sp[i].name);
printf("%s\n",sp[i].name);
}
最佳答案
您应该将 sp
声明为全局范围内的指针,并使用 malloc
在函数 erzeuge
中为其分配内存。
#include <stdlib.h>
#include <stdio.h>
struct spieler {
char name[20];
int age;
};
struct spieler *sp; // Add this
void erzeuge();
int main() {
int anzahl;
printf("Anzahl Spielern: ");
scanf("%d", &anzahl);
erzeuge(anzahl);
printf("Es sind %d Spielern\n", anzahl);
int i;
for(i = 0; i < anzahl; i++){
printf("%d.%s\n", i, sp[i].name);
}
if (sp) {
free(sp);
}
getchar();
return 0;
}
void erzeuge(int anzahl) {
// Add the following line to allocate memory
sp = (struct spieler*) malloc(anzahl * sizeof(struct spieler));
int i;
for (i = 0; i < anzahl; i++) {
// Remove the following line because it create an array of "i" elements
// struct spieler sp[i];
printf("Struct fuer Spieler_%d wurde erzeugt\n", i);
getchar();
printf("Name: ");
scanf("%s",sp[i].name);
printf("%s\n",sp[i].name);
}
}
关于c - C 编程中带有 "struct"的 "for-loop"对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8453158/