c - 返回 char[] 以在 strtok() 函数中使用它

标签 c

我有功能

char *priq_pop(pri_queue q, int *pri)
{
    char *out;
    if (q->n == 1) return 0;

    q_elem_t *b = q->buf;

    out = b[1].data;
    if (pri) *pri = b[1].pri;

    /* pull last item to top, then down heap. */
    --q->n;

    int n = 1, m;
    while ((m = n * 2) < q->n) 
    {
        if (m + 1 < q->n && b[m].pri > b[m + 1].pri)
        {
            m++;
        }

        if (b[q->n].pri <= b[m].pri)
        {
            break;
        }
        b[n] = b[m];
        n = m;
    }

    b[n] = b[q->n];
    if (q->n < q->alloc / 2 && q->n >= 16)
    q->buf = realloc(q->buf, (q->alloc /= 2) * sizeof(b[0]));

    return (char *)out;
}

我需要在 main() 中使用返回值:

int main()
{
    pri_queue qq = priq_new(0);
    char test[] = "test1,test2";
    char *ret;
    int pp;
    char *x;
    char *y;

    priq_push(qq, "test2", 2);
    priq_push(qq, "test,s", 0);

    ret = priq_pop(qq, &pp);
    printf("%s\n\n", ret);

    x = strtok(ret, ",");
    y = strtok(NULL, ",");

    printf("%s\n%s", x, y); 

    return 0;
}

但是使用这段代码,我的程序在到达 x = strtok(ret, ","); 时停止工作。错误在返回值中(在 ret 中),因为如果我使用变量 test,它就可以工作。请问我该如何解决我的问题?

最佳答案

您正在将常量字符串文字推送到此处的队列中:

priq_push(qq, "test2", 2);
priq_push(qq, "test,s", 0);

"test2""test,s" 是字符串文字,您将指向它们的指针推送到您的优先级队列中。字符串文字不可写。

当您从优先级队列中弹出时,您将取回与推送相同的指针,然后将其传递给 strtokstrtok 需要修改传递给它的字符串。但是,因为您向它传递了一个指向字符串文字的指针,所以它会导致异常。

您需要将可写字符串传递给strtok。这需要在将其插入队列之前制作副本(并在完成后释放它),或者在将其从队列中弹出时制作副本(并再次在完成后释放它)它)。

您可以使用 strlenmallocstrcpy 来制作可写副本,或者使用常用的(但非标准的) strdup.

关于c - 返回 char[] 以在 strtok() 函数中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20777591/

相关文章:

c++ - 指针分配时出现段错误

c++ - 圈到圈交点

c - 链接 : making virtual address corresponding to file offset

c - C中这个指针程序中的段错误

c - 用 C 返回数组,不同的方法

c - 为什么在尝试 "cat"我的字符设备驱动程序时收到错误消息?

c++ - 来自第二个线程的 Qt 信号调用有效 -> 对连接的插槽没有影响

c - 分段故障 ? C

c - 即使我将 include 目录添加到项目中,Visual Studio 2017 也无法打开 "SDL.h"

C 将大文件读入 char* 数组太慢