c - C 编程中带有 "struct"的 "for-loop"对象

标签 c for-loop struct

此代码是关于 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/

相关文章:

java - 为什么 Java 中这个简单的数组排序方法在更改初始化时表现不正常?

r - R中带有foreach的两个rbind数据帧的输出列表

csv - 总结csv的内容

C 结构说明

c - memcpy(&a + 1, &b + 1, 0) 是在 C11 中定义的吗?

c - 旋转的弦

c - 用 C 编写着色器错误检查器

python - 在 Python 的 for 循环中使用 dict.get() 方法时如何传递变量

vector - 为什么在 Debug模式下访问大型结构向量的元素比访问较小的结构向量要慢?

c - 从功能 STM32F051C6 返回时出现问题(硬故障)