error C2440: '=' : cannot convert from 'void *' to 'struct stu *'
Conversion from 'void*' to pointer to non-'void' requires an explicit cast
C++ 編譯器(VS 預設以 C++ 編譯 `.cpp`)要求 `void*` 轉換為其他指標型別時**必須顯式強制轉型**。C 語言允許隱性轉換,但 C++ 不允許。
// C++ 風格強制轉型 (推薦)
struct stu *student = static_cast(malloc(sizeof(struct stu)));
// 或 C 風格
struct stu *student = (struct stu*)malloc(sizeof(struct stu));
#include
#include
struct Data {
int day, month, year;
};
struct Stu {
char name[20];
long num;
struct Data birthday;
};
int main() {
struct Stu *student = (struct Stu*)malloc(sizeof(struct Stu));
if (student == NULL) {
fprintf(stderr, "記憶體配置失敗\n");
return 1;
}
printf("Input name, number, year, month, day: ");
if (scanf("%19s", student->name) != 1) goto cleanup;
if (scanf("%ld", &student->num) != 1) goto cleanup;
if (scanf("%d %d %d", &student->birthday.year, &student->birthday.month, &student->birthday.day) != 3) goto cleanup;
printf("\nOutput: name, number, year, month, day\n");
printf("%-20s %10ld %10d/%02d/%02d\n",
student->name, student->num,
student->birthday.year, student->birthday.month, student->birthday.day);
cleanup:
free(student);
return 0;
}
若為 C++ 專案,**完全避免 `malloc`/`free`**,改用 `new`/`delete` 或智慧指標 (`std::unique_ptr`),並用 `std::string` 替代字元陣列。