c - 运行程序时出现段错误

标签 c pointers segmentation-fault

我已经编写了将字符串解析为单词的代码。这是代码。任何人都可以在这里帮助修复运行时的段错误错误吗?

打电话很有趣:

int main()
{
    int count = 0, i;           // count to hold numbr of words in the string line.

    char buf[MAX_LENTHS];   // buffer to hold the string

    char *options[MAX_ORGS]; // options to hold the words that we got after parsing.

    printf("enter string");

    scanf("%s",buf);

    count = parser(buf,options); // calling parser

    for(i = 0; i < count; ++i)

    printf("option %d is %s", i, options[i]);

    return 0;  
}

调用函数:

int parser(char str[], char *orgs[])
{
    char temp[1000];//(char *)malloc(strlen(str)*sizeof(char));
    int list = 0;

    strcpy(temp, str);

    *orgs[list]=strtok(str, " \t ");

    while(((*orgs[list++]=strtok(str," \t"))!=NULL)&&MAX_ORGS>list)
        list++;

    printf("count =%d",list);

    return list;

}

注意:这些天我正在尝试学习 C,有人可以帮助获得一个好的教程 (pdf) 或网站来学习这些带指针的字符串,并将字符串作为参数发送到函数吗?

最佳答案

您使用的 strtok 有误。

(通常最好根本不要使用 strtok,因为它存在所有问题和陷阱。)

如果您必须使用它,使用strtok 的正确方法是用您想要“标记化”的字符串调用它一次, 然后用 NULL 一次又一次地调用它作为继续解析原始字符串的指示。


我还认为您错误地使用了 orgs 数组。 更改此分配

*orgs[list++]=strtok(str, " \t ");

为此:

orgs[list++]=strtok(str, " \t ");

因为 orgs 是一个字符指针数组。
orgs[x]是一个字符指针,匹配strtok

的返回类型

相反,您指的是 *orgs[x],它只是一个字符。
所以你正在尝试做:

[character] = [character-pointer];

这将导致“very-bad-things™”


最后,请注意,您在循环中每次递增列表两次
所以基本上您只填充偶数元素,而未初始化 orgs 的奇数元素。

每个循环只增加列表一次

基本上,你想要这个:

orgs[list++] = strtok(str, " \t ");

while(( (orgs[list++] = strtok(NULL," \t")) !=NULL) && MAX_ORGS > list)
    /* do nothing */;

PS 你为temp分配了空间,并将strcpy分配给它。
但随后看起来您从未使用过它。
解释 temp 的用途,或将其删除。

关于c - 运行程序时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17703003/

相关文章:

c++ - 尝试分配输出以查看指针和引用输出时,未命名类型错误

c - 不会进入我的功能

perl - 在 Perl 中调试段错误

c - 结构中的 sizeof 错误

c - 指针在不应该受到影响的函数调用上受到影响

c++ - printf 的 #%ld!\n 的每个元素是什么意思?

c++ - 存储对象列表

c - 是什么导致此函数中出现段错误?

c - Julia - 结构内部的 C 结构在 Julia 中存储为指针

c++ - 如何实现内存堆