c - 在 C 中访问和输入元素到动态结构数组中

标签 c arrays dynamic struct dynamic-arrays

我正在尝试访问动态结构数组中的不同元素,但是除了第一个元素之外,我似乎无法访问数组中的任何其他元素。

C文件

#include <stdio.h>
#include <stdlib.h>
#include "tuples.h"

void createTuple();

int main() {
    createTuple();
    return 0;
}

void createTuple(){

    int numOfTup;

    printf("How many tuples would you like to create:\n");
    scanf(" %d", &numOfTup);

    tuple_t *tuples;

    tuples = malloc(numOfTup * sizeof(char) * sizeof(int) * 3);

    if (tuples == NULL){
        printf("Memory allocation failed");
        exit(EXIT_FAILURE);
    }

    for (int j = 0; j < numOfTup; ++j) {

        printf("Enter an identifier for the Tuple: \n");
        scanf(" %c", &tuples[j].identifier);

        printf("TUPLE: %c\n",tuples[j].identifier);

        for (int i = 0; i < 4; ++i) {
            printf("Enter the value for the tuple (C:I:I:I)\n");
            if (i == 0) {
                scanf(" %c", &tuples[j].val0);
            } else if (i == 1) {
                scanf(" %d", &tuples[j].val1);
            } else if (i == 2) {
                scanf(" %d", &tuples[j].val2);
            } else if (i == 3) {
                scanf(" %d", &tuples[j].val3);
            }
        }
    }

}

结构体的头文件

#ifndef TASK2_TUPLES_H
#define TASK2_TUPLES_H

struct tuple{
    char identifier[100];

    char val0;
    int val1;
    int val2;
    int val3;
};

typedef struct tuple tuple_t;


#endif //TASK2_TUPLES_H

我似乎无法访问 tuples[j] 处的结构,因为每当我尝试运行它时,它只保存第一组元素。

此外,每当输入标识符时,编译器都会跳过循环,并且不允许我在结构中输入任何元素。

谢谢。

最佳答案

首先,声明:

tuples = malloc(numOfTup * sizeof(char) * sizeof(int) * 3);
                           //always ==1      why?      why?

应该看起来更像:

tuples = malloc(numOfTup * sizeof(*tuples));

和:

scanf(" %c", &tuples[j].identifier);//wrong format specifier for string
       ^^^   ^                      //and address of ( & ) operator not needed for string.  

应该是:

scanf("%s", tuples[j].identifier);
       ^^   ^

关于c - 在 C 中访问和输入元素到动态结构数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53821129/

相关文章:

c++ - 哪种方式更适合数组访问?

vb.net - 上下文菜单 strip 宽度

html - 使用 removeUI 删除多个元素/使用 tags$div() 为每个变量分配一个 id 包装多个元素

mysql - 向 C 应用程序指示 MySQL 列值更改

c - 当我只能定义一个可变长度数组时,为什么要使用 malloc()?

javascript - JS 如何对数组的索引进行归约求和?

c - 查找数组之间的共同元素(匹配元素)

javascript - Angular 绑定(bind)范围数据到 templateCache

c - 大小();返回嵌入式 C 中指定数组的值的两倍

c - 如何在 C 中获取数组的下一个元素?