c - C 中的子串提取和段错误

标签 c string segmentation-fault

我有这样一个字符串:word1;word2;42;word3-我需要提取除以分隔符的单词并将它们存储在具有以下结构的结构中:

typedef struct Info {
   char *info_one;
   char *info_two;
   char *info_three;
   int number;
} Info;

为了得到单词我写了这个函数:

char *get_words(char *source, char **dest, const char separator)
{
    int length;
    char *substring;

    substring = strchr(source, separator);
    length = strlen(source) - strlen(substring);
    (*dest) = (char *) malloc ((length+1) * sizeof(char));  
    strncpy(*dest, source, length);
    (*(dest + length)) = '\0';
    return substring+1;
}

我从 main 中调用这个函数是这样的:

int main(int argc, char *argv[]) {
   Info *info;
   char *number;
   char *substring;
   char *stringinfo = "dog;cat;12;elephant-";

   info = (Info *) malloc (sizeof(Info));
   substring = stringinfo;

   substring = get_words(substring, &info->info_one, ';');
   substring = get_words(substring, &info->info_two, ';');
   // -------- 
   substring = get_words(substring, &number, ';');
   info->number = atoi(number);
   // --------
   substring = get_words(substring, &info->info_three, '-');

   return 0;
}

我的问题是此代码在处理提取“数字部分”后剩余的子字符串时生成段错误。如果我不在字符串中放入数字,并且很明显,我不调用函数来提取它,那么一切都会顺利进行。我不知道出了什么问题,你能帮我找出错误吗?

最佳答案

您正在使用局部变量:

(*(dest + length)) = '\0';

必须是

(*(*dest + length)) = '\0';

关于c - C 中的子串提取和段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28740488/

相关文章:

c - Unsigned Long Int 在计算 pow 时溢出

python - 如何调试或跟踪DBus?

c# - C#如何获取字符串中的所有其他字符

c - 分割错误 - 自适应霍夫曼树

c++ - 用双指针头节点初始化链表c++

c++ - GetWindowTextW 无法获取宽字符串

java - Java与C之间的Socket通信: Good buffer size

java - 在 Java 中使用 .repeat() 方法时找不到符号(代码在 Netbeans 中运行)

Python 从 DataFrame 字符串字段中去除所有空格

c++ - 级联结构指针测试代码中的段错误