char ***代码无法正常工作

时间:2016-01-18 18:41:03

标签: c arrays pointers char

我需要以这种方式解决这个问题,因为给定的函数需要有这些参数,问题是我在第20个字符串左右读取了核心:

int load(char *filename, char ***words) {
    char **pt = (*words);
    *words = (char **)malloc(sizeof(char*));
    char s[50];

    FILE *f = fopen(filename, "r");
    int i = 0, t;

    while (fscanf(f, "%s", s) == 1) {
        t = strlen(s);
        printf("%d    ", t);
        s[t] = '\0';

        pt = (char **)realloc(pt, sizeof(char*) * (i + 1));
        pt[i] = (char *)realloc(pt[i], sizeof(char) * (t + 1));

        strncpy(pt[i], s, t + 1);
        printf("%s\n", pt[i]);

        i++;
    }
    return 0;
}

我使用pt作为char**来测试它是如何工作的,目标是将***words存储在文本文件中的字符串中:

文本文件:

break
int
case
long
char
continue
return
default
short
do
sizeof
double
static
else
struct
switch
typedef
float
for
unsigned 
goto
while

2 个答案:

答案 0 :(得分:2)

我假设您想将此作为返回参数使用?

char **pt=(*palavras);

在这里,您获得当前值。

pt=(char **) realloc(pt,sizeof(char*)*(i+1));

现在您使用可能的新分配覆盖该值。

你可能错过了

*palavras = pt;

返回此值?否则,您可能会泄漏已分配的内存。

此外,您的realloc位置不正确:

pt[i] = (char *)realloc(pt[i], sizeof(char) * (t + 1));

因为pt[i]的旧值是未定义(如果幸运的话,您的内核或libc将其初始化为NULL,尽管您没有请求内存初始化。< / p>

答案 1 :(得分:1)

数组指针pt应该在从函数返回之前初始化为NULL,最终值存储到*words

此外,在此处重新分配pt[i]时,您未将NULL设置为pt

pt = (char **)realloc(pt, sizeof(char*) * (i + 1));

未初始化超出先前大小的重新分配空间。 以这种方式修复代码:

pt = realloc(pt, sizeof(char*) * (i + 1));
pt[i] = NULL;

您可以使用strdup分配字符串来实际简化代码:

int load(char *filename, char ***words) {
    char **pt = NULL;
    char s[50];
    int i = 0, t;

    FILE *f = fopen(filename, "r");
    if (f != NULL) {
        for (; fscanf(f, "%49s", s) == 1; i++) {
            t = strlen(s);
            printf("%d    ", t);
            pt = realloc(pt, sizeof(*pt) * (i + 1));
            pt[i] = strdup(s);
            printf("%s\n", pt[i]);
        }
    }
    *words = pt;
    return i;
}

我让函数返回加载到words数组中的单词数,否则就无法知道了。

相关问题