动态内存分配反转浮点数打印数组

时间:2015-05-14 18:54:24

标签: c arrays struct floating-point malloc

因此,我是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(){
      ^

2 个答案:

答案 0 :(得分:1)

指针x是存储在数组中的结构的一部分。你可能想要访问你的&#34; x&#34;通过结构。而不是

{{1}}

你是probalby想要

{{1}}

以上这行将编译,但很可能会给你不正确的结果。由于您想要分配它,您希望它是您计划存储在那里的变量的大小,而不是结构的大小。

我应该提到还有其他问题。你不能以这种方式迭代结构。您希望改为迭代数组(结构)的长度。

答案 1 :(得分:0)

您的代码存在很多问题。在尝试这样做之前,我会建议你用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;
 }