我在拆分C中的字符串時遇到了問題。每次嘗試執行我的代碼時,都會出現「分段錯誤」錯誤。但我不太清楚問題是什麼。C - 將字符串拆分成多個部分
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char** string_array = NULL; //string array for the split method
static int split_string(char* string, char* delimiter)
{
char* part = strtok(string, delimiter);//string which is getting split out by strtok
int number_of_parts = 0;//number of strings
/*split string into multiple parts*/
while(part)
{
string_array = realloc(string_array, sizeof(char*)* ++number_of_parts);
if(string_array == NULL)//allocation failed
return -1;
string_array[number_of_parts-1] = part;
part = strtok(NULL, delimiter);
}
/*write final null into string_array*/
string_array = realloc(string_array, sizeof(char*)* (number_of_parts+1));
string_array[number_of_parts] = 0;
return 0;
}
int main()
{
char* string = "string1 string2 string3";
printf("%d", split_string(string, " "));
return 0;
}
@ n.m。同意,但OP很難找到這個參考。 –
請注意,如果/當重新分配失敗時,'old_ptr = realloc(old_ptr,new_size)'構造會泄漏內存。你需要使用'void * new_ptr = realloc(old_ptr,new_size); if(new_ptr == 0){...處理錯誤...} old_ptr = new_ptr;'。這樣,你仍然在'old_ptr'中有一個有效的指針,它仍然可以被釋放。 –