我使用Visual C++ 6.0練習指針人員分配結構變量,下面是我的代碼:麻煩與存儲空間和初始化
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
char first_name[50];
char middle_name[50];
char last_name[50];
int height;
int weight;
}people;
int main()
{
//declare a people structure pointer
people *ppl_ptr;
//allocate memory space for people structure
ppl_ptr = malloc(sizeof(people));
//check if you run out of the heap
if(ppl_ptr==NULL)
{
printf("Out of memory!\n");
return 0;
}
//initialize the unname people varible
(*ppl_ptr)={"bla","bla","bla",192,58};
return 0;
}
,但我得到了一個語法錯誤: C:\C Practice\ch14.c(30) : error C2059: syntax error : '{' Error executing cl.exe.
如果我更換 (*ppl_ptr)={"bla","bla","bla",192,58};
的東西,如 (*ppl_ptr).first_name="bla";
我會得到一個不同的錯誤:
ch14.c
C:\C Practice\ch14.c(30) : error C2106: '=' : left operand must be l-value
Error executing cl.exe.
這個錯誤味精並沒有真正意義的我...這是否曾想到你的人?請讓我知道它爲什麼給我這個錯誤消息。提前致謝。
切向注意:Visual Studio 6已經有14年了,所以在支持C++的新特性方面已經嚴重過時了。我建議你升級到一些現代化的東西(Visual Studio 2010 Express是免費的,並且14年以上是最新的!)。 – 2012-03-31 16:00:18
@OliverCharlesworth這是一個C問題(VC++ 6有一個C編譯器和一個C++編譯器)。我們可以告訴他他正在使用C,因爲他沒有得到編譯器錯誤,因爲沒有投出malloc!但升級編譯器當然是一個好主意,特別是考慮到最近版本的VS Express是免費的。 – 2014-12-08 04:14:40