2010-04-17 82 views
2

我有這樣如何使用的char *爲char []

typedef struct bookStruct 
{ 
    char title[80]; 
    char author[80]; 
} BookType; 

一個結構,我有兩個字符串這樣

char *title = "A Book on C"; 
char *author = "A. Kelly"; 

現在我不能創建一個BookType這樣

BookType book = {title, author}; 

誰能告訴我什麼是錯的?我怎樣才能做到這一點?

回答

6

有兩種可能的解決方案來解決您的問題。其中第一個是在建設的地方使用字符串文字:

BookType book = { "A book on C", "A. Kelly" }; 

在這種情況下,編譯器會將文字複製到相應的變量。如果你不能在初始化使用文字,那麼你就必須自己複製的元素:

BookType book = { 0 }; // 0 initalize 
strncpy(book.title, title, sizeof(book.title)-1); 
strncpy(book.author, author, sizeof(book.author)-1); 
+3

哇,這是毫無意義的堅持認爲函數strncpy比strcpy的「更安全」的宗教信仰的極端的例子。或者可能是一個簡單的「思考o」。使用'sizeof(book.title)-1'作爲限制,或使用strlcpy:你的代碼在任何意義上都沒有「確保大小適合」:-) – 2010-04-17 12:48:13

+0

你是對的。計數應該是'sizeof(book.title)-1'。另一方面,評論並不意味着代碼將確保,但用戶必須確保它在調用方法之前適合。 – 2010-04-17 12:56:54

+0

'MIN(sizeof(book.title)-1,strlen(title)))'是不必要的。 http://stackoverflow.com/questions/2658182/how-to-use-char-as-char/2658217#2658217 – 2010-04-17 13:10:06

2

您必須使用strcpy(如果您知道輸入的長度)或安全函數。

很多其他的答案也造成了同樣的錯誤,使得未終止的字符串成爲安全漏洞的主要來源。

正確的方法是使用安全的字符串拷貝功能,如StringCbCopy或推出自己的(雖然不夠健壯):

// Copy at most n-1 characters to dst, truncating if strlen(src) > n-1 
// and guaranteeing NUL-termination. 
void safe_strcpy(char *dst, const char *src, size_t n) { 
    strncpy(dst, src, n-1); 
    dst[n-1] = 0; // Guarantee NUL-termination. 
} 

然後如下

void f(const char *title, const char *author) { 
    BookType book; 
    safe_strcpy(book.title, title, sizeof book.title); 
    safe_strcpy(book.author, author, sizeof book.author); 
} 
1

你可以用它據我所知,在C中沒有辦法做到這一點。最好的辦法是使用宏:

#define TITLE "A Book On C" 
#define AUTHOR "A. Kelley" 

BookType book {TITLE, AUTHOR}; 

儘管這當然不會有完全相同的效果。

3
void InitBookStruct(BookType *book, const char *title, const char *author){ 
    size_t title_length = sizeof book->title; 
    size_t author_length = sizeof book->author; 

    strncpy(book->title, title, title_length - 1); //-1, make way for null byte 
    strncpy(book->author, author, author_length - 1); 

    book->title[title_length - 1] = 0; 
    book->author[author_length - 1] = 0; 
} 

多種方式來完成,上面就是其中之一。


從手冊頁,

的char *函數strncpy(字符* DEST,爲const char * SRC,爲size_t n)的;

如果src的長度小於n,則strncpy()用空字節填充 dest的其餘部分。

因此,指定(小於)dest的大小就足夠了。

+0

這不保證任何字段的空終止。 – 2010-04-17 13:11:58

+0

@亞歷克斯:謝謝。更新。 – 2010-04-17 13:24:21

2

如果您改變了結構,這樣它應該工作

typedef struct bookStruct 
{ 
    char* title; 
    char* author; 
} BookType; 
+0

適用於C99或C++。 – JRL 2010-04-17 13:08:48