簡體   English   中英

在 c 語言的結構中分配數組

[英]Assign an array in a struct in c language

我有以下代碼:

#include<stdio.h>

struct student {
    int* grades; 
    int num_grades;
};

double* get_means(struct student* arr, int n); // Function Signature

// grade range is: 0 - 100
// assume max number of grades to one student is up to 100
double* get_means(struct student* arr, int n)
{
    arr->grades = 90;
    printf("%d", arr->grades);
}

int main()
{
    struct student s, *p;
    s.grades = malloc(s.num_grades * (sizeof(int)));


    p->grades[0] = 1;
        printf("%d", p->grades[0]);
}

而且我在分配值時遇到問題(值是什么並不重要,它可以是:0、7、50)。

編譯器給了我錯誤:

Error   C4700   uninitialized local variable 's' used
Error   C4700   uninitialized local variable 'p' used

我能做些什么來解決這個問題?

換句話說:如何為結構中的數組賦值?

當您首先嘗試執行 p->grades[0] = 1 時,您需要將 s 的地址分配給 p,而不是嘗試從指針 p 訪問 s。 這里的第二個問題是您嘗試僅通過名稱訪問數組(在 function 中獲取手段),如您所知,數組名稱只是數組的基地址而不是其中的值。 第三個問題是它的 function 沒有返回任何東西,但在原型中它返回指向 double 的指針,我建議你更改它以避免任何不必要的警告或錯誤。 另一個建議是在使用 malloc 時包含 <stdlib.h> 並始終檢查 malloc 不會返回 NULL。

附上固定代碼:

  struct student {
  int* grades; 
  int num_grades;
  };

void get_means(struct student* arr, int n); 

void get_means(struct student* arr, int n)
{
   arr->grades[0] = 90;
   printf("%d", arr->grades[0]);
}

int main()
{
   struct student s, *p;
   s.grades = malloc(s.num_grades * (sizeof(int)));

   /* Option 1 
   s.grades[0] = 1;
   printf("%d", s.grades[0]);
   */
    
   /* Option 2 */
   p = &s;
   p->grades[0] = 1;
   printf("%d", p->grades[0]);
 }

暫無
暫無

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

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