[英]Error working with structs and pointer arrays: incompatible types in assignment
#define STRMAX 50
struct Person {
char sName[STRMAX];
int iAge;
};
typedef struct Person PERSON;
int main() {
PERSON *personen[1];
personen[0]->sName = "Pieter";
personen[0]->iAge = 18;
return 0;
}
此代碼在personen[0]->sName = "Pieter";
上生成錯誤personen[0]->sName = "Pieter";
說分配中的類型不相容 。 為什么?
您不需要指針數組。 嘗試
PERSON personen[1];
就像其他人所說的那樣,請使用strcpy函數!
不要嘗試分配數組。 使用strcpy
將字符串從一個數組復制到另一個數組。
... sName
是一個字符數組,而“ Pieter”是一個const char*
。 您不能將后者分配給前者。 編譯器總是正確的:)
更改
PERSON *personen[1];
至
PERSON personen[1];
並使用strcpy復制字符串。
strcpy(personen[0]->sName,"Pieter");
我同意以上內容,但我認為加入“為什么”也很重要
int a; // is an integer
int *b; // pointer to an integer must be malloced (to have an array)
int c[]; // pointer to an integer must also be malloced (to have an array)
int d[5]; // pointer to an integer bu now it is initialized to an array of integers
要從簡單的指針獲取b和c並給它們提供與d匹配的內存,請使用以下內容為它們提供內存
b = (int *) malloc(sizeof(int)*5);
它將從malloc返回的指針轉換為int指針,並創建一個內存塊,該內存塊的大小是整數的5倍(因此它將像d一樣保存5個整數)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.