我正在尝试访问动态结构数组中的其他元素,但是除第一个元素外,我似乎无法访问该数组中的其他任何元素。
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
我似乎无法在元组[j]上访问该结构,因为每当我尝试运行它时,它只会保存第一组元素。
每当输入标识符时,编译器都会跳过循环,并且不允许我在结构中输入任何元素。
谢谢。
答案 0 :(得分:0)
对于初学者,该语句:
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);
^^ ^
答案 1 :(得分:-1)
您的代码有几个问题:
101 * sizeof(char) + 3*sizeof(int)
个字节的内存。实际上,这可能不够用,因为编译器可能会填充该结构以更好地与内存对齐。因此,实际大小可能更大。安全的做法是分配sizeof(tuple_t)
个字节scanf
函数读取的是字符,而不是字符串。使用%s
读取字符串。另外,scanf期望指向由其相应格式说明符指定的类型的已分配对象的指针,在我们的示例中,%s
是字符串,因此类型应为char *
。因此,参数应为tuples[j].identifier
,而不是&tuples[j].identifier
总体:
#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(tuple_t));
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("%s", tuples[j].identifier);
printf("TUPLE: %s\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);
}
}
}
}