I have the following piece of code (which splits a string by a delimiter)
我有以下代码(用分隔符拆分字符串)
void explode(const char *input, const char *delim)
{
char *local = strdup(input);
char *token;
while ((token = strtok_r(local, delim, &local))) {
puts(token);
}
}
Instead of printing out the strings, I would like to have them stored in an array of arrays. I'm somewhat new to the more advanced concepts, I've been getting too much segfaults for hours. What would you do in this situation?
我希望将它们存储在一个数组数组中,而不是打印出字符串。我对更先进的概念有些新意,我已经得到了太多的段错误。在这个情况下,你会怎么做?
1 个解决方案
#1
0
You don't know the size of the array before hand so you should initialize it to some fixed sensible size (say 16?) and keep an index variable to point to the next available slot in the array to store the next variable. If the index variable becomes equal to 15 (one minus the initial size), you need to use realloc to allocate more memory and update the size variable. Keep reallocating till you are not done with the string. Here is some pseudo code:
您之前不知道数组的大小,因此您应该将其初始化为某个固定的合理大小(例如16?)并保留索引变量以指向数组中的下一个可用插槽以存储下一个变量。如果索引变量等于15(一减去初始大小),则需要使用realloc分配更多内存并更新size变量。继续重新分配,直到你没有完成字符串。这是一些伪代码:
size_t array_size = 16;
size_t index = 0;
char **arr = malloc(array_size * sizeof(char *));
while ((token = strtok_r(local, delim, &local))) {
if (index == array_size - 1) {
array_size += 16;
arr = realloc(arr, array_size);
/* add error check */
}
arr[index++] = token;
}
You should make sure that you free the memory allocated once you are done with it.
完成后,应确保释放分配的内存。
#1
0
You don't know the size of the array before hand so you should initialize it to some fixed sensible size (say 16?) and keep an index variable to point to the next available slot in the array to store the next variable. If the index variable becomes equal to 15 (one minus the initial size), you need to use realloc to allocate more memory and update the size variable. Keep reallocating till you are not done with the string. Here is some pseudo code:
您之前不知道数组的大小,因此您应该将其初始化为某个固定的合理大小(例如16?)并保留索引变量以指向数组中的下一个可用插槽以存储下一个变量。如果索引变量等于15(一减去初始大小),则需要使用realloc分配更多内存并更新size变量。继续重新分配,直到你没有完成字符串。这是一些伪代码:
size_t array_size = 16;
size_t index = 0;
char **arr = malloc(array_size * sizeof(char *));
while ((token = strtok_r(local, delim, &local))) {
if (index == array_size - 1) {
array_size += 16;
arr = realloc(arr, array_size);
/* add error check */
}
arr[index++] = token;
}
You should make sure that you free the memory allocated once you are done with it.
完成后,应确保释放分配的内存。