gpt4 book ai didi

c - 双指针循环中的段错误

转载 作者:行者123 更新时间:2023-11-30 16:42:22 25 4
gpt4 key购买 nike

这是我的代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main ()
{
char str[] ="a,b,c,d,e";

struct stri {
int i;
char *data;
};
struct stri **pstri = NULL;
char *pch;
pch = strtok (str,",");
int i = 0;
while (pch != NULL)
{
printf("before: %s\n", pch);
pstri = realloc(pstri, (i + 1) * sizeof(struct stri*));
struct stri *s = malloc(sizeof(struct stri));
s->i = i;
s->data = strdup(pch);
pstri[i] = s;
i++;
pch = strtok (NULL, ",");
}
//update
// should I realloc here too?
pstri[i] = NULL;
//update


int j = i;
for(i = 0; i<j; i++) {
printf("after: %d=>%s\n", pstri[i]->i, pstri[i]->data);
}

struct stri *k = NULL;
while(k = *pstri++) {
printf("after2: %d=>%s\n", k->i, k->data);
}

return 0;
}

输出为

before: a
before: b
before: c
before: d
before: e
after: 0=>a
after: 1=>b
after: 2=>c
after: 3=>d
after: 4=>e
after2: 0=>a
after2: 1=>b
after2: 2=>c
after2: 3=>d
after2: 4=>e
Segmentation fault

最佳答案

pch = strtok (NULL, ",") 时,While 循环退出使 pch 为 NULL,但我们尚未在 i = 5 设置 NULL对于 pstri。如果您设置j = 6,也会发生同样的段错误。而不是j = i因为i正在保护这个after:环形。

关于c - 双指针循环中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45851643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com