這是我的函數:分割字符串以140字符塊
char** split_string(char* message){
int i = 0;
int j = 0;
int numberOfMsgs = 0;
int charsInLastMsg = (int)(strlen(message)%140);
if((int)strlen(message) > 140*4){
return NULL;
}
if((int)(strlen(message)%140)){
numberOfMsgs = (int)(strlen(message)/140) + 1;
}
else{
numberOfMsgs = (int)(strlen(message)/140);
}
printf("message length = %d, we will have %d messages, and last msg will have %d characters\n", (int)strlen(message), numberOfMsgs, charsInLastMsg);
char **m = malloc(numberOfMsgs * sizeof(char*));
for (j =0 ; j <= numberOfMsgs; j++){
m[j] = malloc(141 * sizeof(char));
}
for(i=0;i<numberOfMsgs;i++){
if(i == numberOfMsgs - 1){
memcpy(m[i], message + (140*i), charsInLastMsg);
m[i][charsInLastMsg] = '\0';
}
else{
memcpy(m[i], message + (140*i), 140);
m[i][140] = '\0';
}
printf("m%d = %s\n", i, m[i]);
}
return m;
}
哪個我打電話是這樣的:
char* message = "1, 2, 3, 4, 5, 6, 7, 8, 9 and 10, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100.";
int i=0;
char** m = split_string(message);
while(*m){
printf("string%d = %s\n", i, m[i]); //Problem at this line.
m++;
}
但是,當我運行它,我得到一個分段錯誤在上面指出的線上。如果我不打印,程序運行良好,所以我認爲split_string()函數是正常的。
我在做什麼錯?我是一個新手,plz的幫助。
/************************************預計O/P ***** *****************************/
我想將字符串分成140個字符串,如下所示:
string0 = 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36
string1 = , 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71
string2 = , 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100.
你出去在數組邊界的'M' ..分配'米[J] = malloc的(140 *的sizeof(char)的)',然後嘗試'米[i] [140] ='\ 0';''m'從'0'到'139' – Haris 2014-10-28 11:11:26
問題不在printf中,它是split_string函數不起作用的結果。順便說一句,你的預期產出是多少? – 2014-10-28 11:12:56
感謝您指出緩衝區溢出。我編輯了這個問題。請看一下。 順便說一句,split_string()中的printf工作正常。 – Zaxter 2014-10-28 11:30:25