在C數組中不可分配,但在第36行(我也註釋過的行)中,我給數組分配了一個值,名稱爲,但沒有得到任何錯誤。這是爲什麼發生?此外,除了這個莫名其妙的事情,如果您檢查我的freeStudents功能是否正常工作,我將非常感激。謝謝你的時間傢伙!在C數組中不可賦值,爲什麼這個程序工作?
#include <stdio.h>
#include <stdlib.h>
#define MAX_NAME 50
struct students
{
char name[MAX_NAME];
float average;
};
void storeStudents(struct students *lst, int n);
void printStudents(struct students *lst, int n);
void freeStudents(struct students *lst);
int main(void)
{
int n;
printf("How many students you wanna store? ");
scanf("%d", &n);
struct students *list;
list = (struct students *)malloc(n*sizeof(struct students));
storeStudents(list,n);
printStudents(list,n);
freeStudents(list);
return 0;
}
void storeStudents(struct students *lst, int n)
{
int i;
for(i=0;i<n;i++)
{
printf("Name of student: ");
scanf("%s", &(lst[i].name)); //In C arrays are not assignable, so why is this line working?
printf("Average of student: ");
scanf("%f", &(lst[i].average));
}
printf("\n");
}
void printStudents(struct students *lst, int n)
{
int i;
for(i=0;i<n;i++)
{
printf("Name: %s\tAverage: %.2f", lst[i].name, lst[i].average);
printf("\n");
}
}
void freeStudents(struct students *lst)
{
free(lst);
}
如果啓用編譯器警告,您將看到實際發生了什麼:https://ideone.com/7JPJFH –
Oliver Charlesworth代碼塊編譯器不會給我提供任何警告/錯誤.. –
這是什麼意思?數組不可分配「?數組包含的內容顯然是可變的,因此您可以爲它的一個元素指定一個新值。你在哪裏讀過「數組不可分配」? –