C读取文件并切割成二维字符串数组

标签 c

我想读取 .dat 文件并将这些信息切割成 2 个数组: pList是产品列表 eqList为设备列表

文件格式如下:

productName equipment_a equipment_b
productName equipment_c equipment_d equipment_e
productName equipment_b equipment_d equipment_f
productName equipment_c
productName equipment_a equipment_f

What is the problem?

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

#define lineLength 2048

int main()
{
    int a=0,b=0,c=0;
    char fileBuf[100], *pList[100], *eqList[100][100], *tempStr, delimilator[2] = " ";

    while ( fgets(fileBuf,lineLength,stdin) != NULL){
        tempStr = strtok(fileBuf,delimilator);
        pList[a] = malloc( strlen(tempStr) + 1);
        strcpy(pList[a], tempStr);

        for(b=0;tempStr != NULL;b++){
            tempStr = strtok(NULL,delimilator);
            eqList[a][b] = malloc( strlen(tempStr) + 1); //problem here
            strcpy(eqList[a][b], tempStr);               //problem here
        }
        a++;
    }

    return 0;
}

最佳答案

您之前使用 strok 返回值来检查它是否为 != NULL。在最后一次迭代中,它将调用 Undefined Behavior

你的循环可能是这样的

while (fgets(fileBuf, sizeof(fileBuf), stdin) != NULL)
{
    tempStr = strtok(fileBuf,delimilator);
    pList[a] = malloc( strlen(tempStr) + 1);
    strcpy(pList[a], tempStr);

    tempStr = strtok(NULL,delimilator);

    b=0;

    while (tempStr != NULL)
    {
        eqList[a][b] = malloc( strlen(tempStr) + 1);
        strcpy(eqList[a][b], tempStr);  

        tempStr = strtok(NULL,delimilator);

        b++;
    }

    a++;
}

关于C读取文件并切割成二维字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43096554/

相关文章:

c - 将未指定数量的命令行输入放入 C 中的数组中

c - 如何打印void * ioremap_nocache()的返回值?

c - 在 C 中实现线程屏障和屏障重置的正确方法是什么?

c++ - 如何表示指向地址空间开头的指针?

我可以返回指向主函数的本地指针吗?

python - 将一组 3 channel 图像从 Python 读取到二维数组以在 C 中使用的有效方法

c - 查找数组中的对称性

c - 'C' 二维数组的段错误

c - 为什么在此代码中会出现分段转储错误?

c - 使用 C TCP 套接字, 'send' 可以返回零吗?