所以我是c的新手,并在数组中使用内存分配。我正在尝试创建一个程序,该程序将使用Malloc动态分配空间来逆转浮点数的数组。
#include <stdio.h>
#include <stdlib.h>
struct Rec {
float * x;
int size;
};
int main(){
struct Rec a[50];
int i, y;
printf("Enter the number of floating point numbers: ");
scanf("%d", &y);
x = malloc(y * sizeof(struct));
printf("Enter 5 floating point numbers: n");
for(i = 0; i < sizeof(struct); i++){
scanf("%.3f", &x[i]);
}
printf("The numbers in reverse order are: n");
for(i = --sizeof(struct); i >= 0; i--){
printf("%f n", a[i]);
}
}
在编译期间,生成以下错误:
error: use of undeclared identifier 'x'
*x = malloc(y * sizeof(struct);
^
test.c:14:25: error: declaration of anonymous struct must be
a definition
*x = malloc(y * sizeof(struct);
^
test.c:14:32: error: type name requires a specifier or qualifier
*x = malloc(y * sizeof(struct);
^
test.c:14:31: error: type name requires a specifier or qualifier
x = malloc(y * sizeof(struct));
^
test.c:14:24: note: to match this '('
*x = malloc(y * sizeof(struct);
^
test.c:25:3: error: expected '}'
}
^
test.c:9:11: note: to match this '{'
int main(){
^
您的指针X是存储在数组中的结构的一部分。您可能想通过结构访问" X"。所以而不是
x = malloc(y * sizeof(struct));
您可能想要
a[some index].x = malloc(y * sizeof(struct));
以上行将编译,但很可能会给您带来错误的结果。由于您想分配它,因此您希望它是您打算存储在此处的变量的大小,而不是结构的大小。
我应该提到还有其他问题。您不能以这种方式迭代结构。您想改用(结构)的阵列长度。
您的代码有很多问题。我建议您在尝试执行此操作之前使用C基础知识进行更多练习。这是您可能想实现的代码的近似:
#include <stdio.h>
#include <string.h>
// This structure can hold array of floats - and their size
struct Rec
{
float * x;
int size;
};
int main()
{
// Declare variable of type rec
struct Rec a;
int i, y;
// How many floats to store? This could also be stored in a.size instead of y
printf("Enter the number of floating point numbers: ");
scanf("%d", &y);
// Create and populate dynamic array
a.x = malloc(y * sizeof(float));
printf("Enter floating point numbers: n");
for(i = 0; i < y; i++)
{
scanf("%.3f", &a.x[i]);
}
// Print
printf("The numbers in reverse order are: n");
for(i = y-1; i >= 0; i--)
{
printf("%f n", a.x[i]);
}
free(a.x);
return 0;
}