[英]C read file & cut into 2D string array
我想讀取一個.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
問題是什么?
#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
。 在最后一次迭代中,它將調用未定義行為
你的循環可能像
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++;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.