简体   繁体   English

我试图制作一个字符串数组,但是现在我的代码出现问题,我不知道如何解决

[英]I tried to make an array of strings and now I have an issue with my code which I don't know how to fix

I'm trying to make an array of strings by using pointers but for some reason (which I hope you would know) the program is crashing after I type the second string. 我试图通过使用指针来创建一个字符串数组,但是由于某种原因(我希望您会知道),我键入第二个字符串后程序崩溃了。 I have been trying for hours to find what's wrong with this code and I'm hoping for your help! 我已经尝试了数小时,以查找此代码出了什么问题,希望能对您有所帮助! During debugging, after I realloced the input it says "error reading characters of string." 在调试期间,重新分配输入后,它显示“读取字符串的错误”。 Here is the code: 这是代码:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>


int main()
{
    char **input = (char **)calloc(1, sizeof(char)), ch;
    *input = (char *)calloc(1, sizeof(char));
    int size = 1,sizeinput=1,current = 0,currentarr=0,i=0,j=0;
    while (i<5)
{

    printf("please enter a word\n");
    scanf("%c", &ch);
    while (ch != '\n')
    {
        *(input+i) = (char*)realloc(*(input+i), (size++)*sizeof(char));
        *(*(input + i) + j++) = ch;
        scanf("%c", &ch);
    }

    *(*(input + i) + j) = '\0';
    j = 0;
    input = (char**)realloc(input, (sizeinput++)*sizeof(char*));
    i++;
    }
    free(input);
}

(char **)calloc(1, sizeof(char))

should be 应该

(char **)calloc(1, sizeof(char*))

Also, after you reallocate input , the last element is an uninitialized pointer! 同样,在重新分配input ,最后一个元素是未初始化的指针! Add this at the end of the loop, so it points to something useful and which you can reallocate later: 在循环的末尾添加它,这样它指向有用的东西,以后可以重新分配:

input[sizeinput - 1] = calloc(1, sizeof(char));

Cosmetic issues: 外观问题:

There's no need to cast the results of calloc and realloc - although doing so won't prevent your program from working, it does make it uglier. 无需callocrealloc的结果-尽管这样做不会阻止程序正常运行,但确实会使程序更难看。

Also, you can use input[i] instead of *(input + i) and input[i][j] instead of *(*(input + i) + j) - again, it won't affect how your program executes, but it can make it easier to read. 另外,您可以使用input[i]代替*(input + i)input[i][j]代替*(*(input + i) + j) -同样,它不会影响程序的执行方式,但可以使其更易于阅读。

The problem is happening due to a reallocation happening in non-allocated memory. 由于未分配的内存中发生重新分配,因此出现了问题。 Consider your original code. 考虑您的原始代码。 When you call realloc for the first time, you call it for *(input + i) , which was previously allocated because i is zero at this point. 第一次调用realloc时,您将它称为*(input + i) ,因为之前i为零,所以先前已对其进行了分配。 This allocation happens in the second line of your main function. 这种分配发生在main函数的第二行。 The problem is that you never allocate for position 1, which you try to (re!)allocate later. 问题在于,您永远不会分配位置1,您稍后会尝试重新分配它。 This fixes it: 可以解决此问题:

int main()
{
    char **input = (char **)calloc(1, sizeof(char)), ch;

    // Don't do it here
    //*input = (char *)calloc(1, sizeof(char));

    int size = 1,sizeinput=1,current = 0,currentarr=0,i=0,j=0;

    while (i<5)
    {
        printf("please enter a word\n");
        scanf("%c", &ch);

        // Do it here instead
        *(input + i) = (char *)calloc(1, sizeof(char));

        while (ch != '\n')
        {
            // Now this reallocation is actually being given something that was allocated before
            *(input+i) = (char*)realloc(*(input+i), (size++)*sizeof(char));
            *(*(input + i) + j++) = ch;
            scanf("%c", &ch);
        }

        *(*(input + i) + j) = '\0';
        j = 0;
        input = (char**)realloc(input, (sizeinput++)*sizeof(char*));
        i++;
    }

    free(input);
}

There are several other issues with this, but as my first suggestion would be to take a different approach I'll leave other issues off the discussion. 与此相关的还有其他一些问题,但是由于我的第一个建议是采用其他方法,因此我将不再讨论其他问题。 Let me know if you are interested, anyway. 无论如何,请让我知道。

Note: This causes one extra reallocation per loop. 注意:这会导致每个循环额外分配一个。 But as I said, it's just a quick fix. 但是正如我所说,这只是一个快速修复。

the following code incorporates the comments, compiles cleanly, uses a function: cleanup() which I did not define, however, cleanup() will pass each word to free() then pass the 'array of pointers to char' to free() 下面的代码合并了注释,进行了干净地编译,使用了一个函数: cleanup()我未定义,但是cleanup()会将每个单词传递给free()然后将“指向char的指针数组”传递给free()

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//#include <conio.h>

// prototypes
void cleanup( char ** input );

int main()
{
    char **input = calloc(1, sizeof(char*));
    char ch;
    *input = calloc(1, sizeof(char));
    size_t size = 1;
    size_t sizeinput=1;
    int i=0;
    int j=0;

    while (i<5)
    {

        printf("please enter a word\n");
        if( 1 != scanf("%c", &ch) )
        {
            perror( "scanf failed" );
            cleanup( input );
            exit( EXIT_FAILURE );
        }

        while (ch != '\n')
        {
            size++;
            char *temp = realloc(*(input+i), size);
            if( NULL == temp)
            {
                perror( "realloc for word failed" );
                cleanup( input );
                exit( EXIT_FAILURE );
            }
            *(input+i) = temp;

            *(*(input + i) + j) = ch;
            j++;

            if( 1 != scanf("%c", &ch) )
            {
                perror( "scanf failed" );
                cleanup( input );
                exit( EXIT_FAILURE );
            }

        }

        // NUL terminate word
        *(*(input + i) + j) = '\0';
        j = 0;

        sizeinput++;
        char** lineTemp = realloc(input, sizeinput*sizeof(char*));
        if( NULL == lineTemp )
        {
            perror( "realloc failed" );
            cleanup( input );
            exit( EXIT_FAILURE );
        }

        input = lineTemp;
        i++;
    }
    free(input);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我很确定我在递归 function 中有 memory 泄漏,但我不知道如何修复它 - I am pretty sure I have a memory leak in a recursive function but I don't know how to fix it 一个空的 for 循环修复了我的代码,但我不知道如何 - An empty for loop fixed my code but I don't know how 我的代码不起作用,我不知道为什么;-; - my code does not work and I don't know why ;-; 我在C代码中遇到错误:二进制表达式的操作数无效(&#39;long long(int)&#39;和&#39;int&#39;)我不知道如何修复 - I am getting an error in C code: invalid operands to binary expression ('long long (int)' and 'int') and I don't know how to fix 我的代码给出了段错误。 我不知道如何调试,甚至不知道错误在哪里 - My code gives segfault. I don't know how to debug or even find where the error is 为什么我不必为const变量制作malloc? - Why don't I have to make malloc for my const variables? 我的阶乘和幂函数在不应该且不知道如何解决的情况下输出数百万的数字(在c中) - My factorial and power functions output a number in the millions when it shouldn't and I don't know how to fix it(in c) 我收到一条错误消息,我不知道如何解决 - I am getting an error message that I don't know how to fix 如何修复此代码以创建字符串数组? - How do I fix this code to create an array of strings? 我还被告知在我的代码中使用: int get_input(char message[]) 但我不知道如何使用它 - i was also told to use: int get_input(char message[]) in my code but i don't know how to use it
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM