簡體   English   中英

將動態內存分配給結構數組

[英]Allocating dynamic memory to a Structures Array

我正在嘗試回答我有要求“ n”坐標的作業,然后構建具有該大小的結構坐標數組。 每個坐標結構都有兩個來自double類型的變量。

我嘗試從用戶那里獲取n的輸入,並通過一條if語句進行檢查,首先將其設置為大於0以避免任何失敗

printf("Enter amount of coordinates:\n");
scanf_s("%d", &n);
if (n > 0) {
    coordinates cordArray = (coordinates *)malloc(cordArray * sizeof(n));

}

可以預期的是,在從用戶獲取n值之后,將正確的大小分配給structs數組。 我得到的錯誤是“嚴重性代碼描述項目文件行抑制狀態錯誤(活動)E0415不存在合適的構造函數來從“坐標*”轉換為“坐標”

大概

 coordinates cordArray = (coordinates *)malloc(cordArray * sizeof(n)); 

必須替換為

coordinates * cordArray = (coordinates *)malloc(sizeof(coordinates) * n);

因為您用coordinates *分配了一個coordinates ,並且cordArray是未知的,甚至它也可能無法轉換為size_t (您未提供其定義)


順便說一句,您在C ++中,為什么要使用C數組,您可以通過新方法對其進行分配,從而允許為每個條目調用坐標的構造函數,或者更好地使用std::vector來更改大小,訪問大小等


關於您的評論,該程序將編譯並運行:

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

typedef struct { 
  double x;
  double y;
}coordinates;

int main()
{
  printf("Enter amount of coordinates:\n");

  int n;

  if (scanf("%d", &n) != 1)
    puts("invalid number");
  else if (n <= 0)
    puts("expected a positive number");
  else {
    coordinates * cordArray = (coordinates *) malloc(sizeof(cordArray) * n);

    if (cordArray == NULL)
      printf("cannot allocate memory, probably %d too large\n", n);
    else {
      int i;

      for (i = 0; i < n; i++) { 
        printf("Please enter coordinates for coordinates #%d:\n", i + 1);
        if (scanf("%lf%lf", &cordArray[i].x, &cordArray[i].y) != 2){
          puts("invalid values");
          return -1;
        }
      }
    }
  }
}

注意這是C代碼,為什么要使用標簽C ++?

pi@raspberrypi:/tmp $ g++ -pedantic -Wall -Wextra c.cc
pi@raspberrypi:/tmp $ ./a.out
Enter amount of coordinates:
2
Please enter coordinates for coordinates #1:
1 2
Please enter coordinates for coordinates #2:
3 4

@bruno已經顯示了使用malloc分配內存的正確方法。 但是,這可以在操作員new[]幫助下更簡單地完成,該操作符自動計算所需的內存量。

coordinates *cordArray = new coordinates[n];

要釋放內存,請使用運算符delete[]

delete[] cordArray;

C ++分配方式的另一個優點是,它為新創建的對象調用構造函數。 (如果有任何構造函數,那就是。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM