2009-11-26 89 views
1

我有一個包含名爲char * text的成員的結構體。在從結構中創建一個對象後,如何將文本設置爲字符串?如何設置字符串類型的結構成員

+0

C中的對象,C中的字符串?我認爲你需要澄清你的問題多一點:) – HyLian 2009-11-26 08:15:35

+0

@HyLian:C中的對象?是的,在C中,存儲中的所有數據都稱爲「對象」。 C中的字符串?當然,C中有字符串。 – AnT 2009-11-26 10:28:49

回答

5

如果你的結構是一樣

struct phenom_struct { 
    char * text; 
}; 

,你給它分配

struct phenom_struct * ps = malloc (sizeof (phenom_struct)); 

然後檢查ps值後不爲空(零),這意味着 「失敗」,您可以將文本設置爲像這樣的字符串:

ps->text = "This is a string"; 
0
typedef struct myStruct 
{ 
    char *text; 
}*MyStruct; 

int main() 
{ 
    int len = 50; 
    MyStruct s = (MyStruct)malloc(sizeof MyStruct); 
    s->text = (char*)malloc(len * sizeof char); 
    strcpy(s->text, "a string whose length is less than len"); 
} 
0

示例:

struct Foo { 
    char* text; 
}; 

Foo f; 
f.text = "something"; 

// or 
f.text = strdup("something"); // create a copy 
// use the f.text ... 
free(f.text); // free the copy 
+0

語法錯誤無處不在... 其「struct Foo f」和「f.text」 – 2009-11-26 08:20:11

+0

@ammoQ,ooooops。謝謝。 – 2009-11-26 08:24:50

1

您的結構成員不是一個真正的字符串,而是一個指針。您可以通過

o.text = "Hello World"; 

設置指向另一個字符串,但你一定要小心,至少長的字符串必須生活爲對象。如其他答案中所示使用malloc是一種可行的方法。在許多情況下,在結構中使用char數組更爲理想。即代替

struct foobar { 
    ... 
    char *text; 
} 

使用

struct foobar { 
    ... 
    char text[MAXLEN]; 
} 

這顯然要求您知道該字符串的最大長度。

相關問題