2

我有字符串数组,我想在数组中复制字符串。它的工作时间比程序停止工作的时间长,我知道问题出在复制字符串中。因为如果我用复制注释行,程序可以正常工作。这是我的代码:

FILE *fsource = fopen(source, "rb");
char fname[256], **files, mybuf[BUFSIZ];
files = allocate2d(files, count_files);

clear(fname);

reading = fread(mybuf, 1, BUFSIZ, fsource);
while(reading)
{
    for(i = 0; i < reading; i++)
    {
       if(mybuf[i] == 20)
       {
          while(1)
            {
                if(i < reading)
                {
                    if(mybuf[i] == 0)
                    {
                        clear(files[ifiles]);
                        strcat(files[ifiles++], fname); // here is problem :(
                        //append_string(files[ifiles++], fname); // also doesn't work

                        clear(fname);
                        break;
                    }

                    append_char(fname, mybuf[i++]);
                }
                else
                {
                    break;
                }
            }
       }

       clear(fname);
    }

    reading = fread(mybuf, 1, BUFSIZ, fsource);
}

char** allocate2d(char **arr, unsigned int size)
{
    unsigned int i = 0;
    arr = malloc(size * sizeof(char));

    for(i = 0; i < size; i++)
    {
        arr[i] = malloc(256);
    }

return arr;
}
4

2 回答 2

1

allocate2d

arr = malloc(size * sizeof(char));

应该

arr = malloc(size * sizeof(char*));

因为你想为size指针分配空间。

arr[i] = malloc(256);

应该更好

arr[i] = calloc(256, sizeof(char));

以确保strcat找到一个 0 字符。(注:sizeof(char)只是写 1 的另一种方式。)

于 2013-01-05T22:04:40.253 回答
1

您必须在 中修复分配allocate2d()。如果你想分配一个指针数组

arr = malloc(size * sizeof(char*));
于 2013-01-05T22:04:48.577 回答