c - 字符串数组,C中写入数据失败

标签 c arrays string

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

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;
}

最佳答案

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 的另一种写法。)

关于c - 字符串数组,C中写入数据失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14176866/

相关文章:

javascript - 简单的 Javascript 替换为循环

将 IP 地址从 char * 转换为 uin32_t

c - 文件程序 - fseek 不工作

c - 修改作为参数传递的* int []

python - numpy中数组之间的映射

java - 进行比较的最坏和最好的情况

java - 无法对基本类型 boolean 调用 equals(boolean)

c# - 在 SICP 中,它表示即使递归调用实际上是迭代的,C 中的内存消耗也会增加。为什么?

c++ - 指针间接检查无效内存访问和段错误

c - 在C中查找字符数组的保留内存大小