拳心向上,sizeof(char)
是總是 1,你不不需要乘以它。
其次,當你爲一個字符串分配房間,你必須使用:
malloc (strlen (string) + 1);
換句話說,你需要空間在末尾的空字節。
第三,你似乎混淆了字符指針和字符指針指針。 stored_
是單個字符塊,而stored_[1]
只比stored_[0]
只有一個字節,這意味着您將沒有足夠的空間存儲字符串。
stored_[n], n=: 0 1 2 3
+---+---+---+---+
| | | | |...
+---+---+---+---+
each of these cells is a single byte.
你要麼必須管理字符自己的單塊,留下足夠的空間,每一個元素(通過使用稀疏索引),或具有字符指針與索引0,1,2,依此塊打開,但你必須分別管理字符串分配。
下面的代碼顯示如何做到這一點後者:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main (void) {
// An array of char pointers (C strings).
char **stored_ = NULL;
char testMessage[15];
int i;
// Populate them.
for (i = 0; i < 10; i++) {
sprintf (testMessage,"Message::%i",i);
printf ("string is:%s;length is %i\n",testMessage,strlen(testMessage));
// Reallocate array of char *, allocate room for string, then store it.
stored_ = realloc (stored_,sizeof (char*) * (i + 1));
stored_[i] = malloc (strlen (testMessage) + 1);
strcpy (stored_[i], testMessage);
}
這是它的肉,字符指針分開從形成C字符串的字符的實際陣列的陣列的分配。
然後下面的代碼打印它們並清理。
// Print them.
for (i = 0; i < 10; i++) {
printf("inside:|%s|\n",stored_[i]);
}
// Free all memory and return.
for (i = 0; i < 10; i++) {
free (stored_[i]);
}
free (stored_);
return 0;
}
輸出是如預期:
string is:Message::0;length is 10
string is:Message::1;length is 10
string is:Message::2;length is 10
string is:Message::3;length is 10
string is:Message::4;length is 10
string is:Message::5;length is 10
string is:Message::6;length is 10
string is:Message::7;length is 10
string is:Message::8;length is 10
string is:Message::9;length is 10
inside:|Message::0|
inside:|Message::1|
inside:|Message::2|
inside:|Message::3|
inside:|Message::4|
inside:|Message::5|
inside:|Message::6|
inside:|Message::7|
inside:|Message::8|
inside:|Message::9|
在該方法中,每個小區是一個指向字符數組,單獨分配(其保持C字符串):
stored_[n], n=: 0 1 2 3
+---+---+---+---+
| | | | |...
+---+---+---+---+
| | | | +----------------------+
| | | +---> | character array here |
| | | +----------------------+
| | | +----------------------+
| | +-------> | character array here |
| | +----------------------+
| | +----------------------+
| +-----------> | character array here |
| +----------------------+
| +----------------------+
+---------------> | character array here |
+----------------------+
段錯誤發生在哪一行? – 2011-12-21 05:23:17
您需要爲末尾的空終止字符('\ 0')添加額外空間。 – 2011-12-21 05:32:20