我的目标是从一百多个“序列”(非技术术语)中读取二进制文件,每个序列包含一个char1(要跟随的字符串的长度),string1,char2,string2。这里的关键似乎是动态内存分配,指针和循环。我就这样做了:
char *ColumnNameLength = (char *) malloc(Repetitions * sizeof(char));
char *DataTypeLength = (char *) malloc(Repetitions * sizeof(char));
char **ColumnName = (char **) malloc(Repetitions * sizeof(char));
char **DataType = (char **) malloc(Repetitions * sizeof(char));
for (int ctr = 0; ctr <= Repetitions ; ColumnNameLength[ctr] = DataTypeLength[ctr] = NULL, ctr++)
;
for (int ctr = 0; ctr <= Repetitions ; *(ColumnName+ctr) = DataType[ctr] = NULL, ctr++)
;
for (int ctr = 0; ctr <= FieldCount; ctr++)
{
fread((ColumnNameLength + ctr), sizeof(char), 1, pInfile);
*(ColumnName + ctr) = (char *) malloc(ColumnNameLength[ctr] * sizeof(char));
fread(ColumnName[ctr], sizeof(char), ColumnNameLength[ctr], pInfile);
//I should add '\0' at the end of each read string, but no idea how
fread((DataTypeLength + ctr), sizeof(char), 1, pInfile);
*(DataType + ctr) = (char *) malloc(DataTypeLength[ctr] * sizeof(char));
fread(&DataType[ctr], sizeof(char), DataTypeLength[ctr], pInfile);
//I should add '\0' at the end of each read string, but no idea how
}
不幸的是,这不起作用,我甚至不知道是否要开始调试。任何建议将不胜感激。
答案 0 :(得分:1)
sizeof(char*)
而非sizeof(char)
unsigned char
来表示长度,以避免信号混淆。'\0'
分配一个字符。ColumnName[ctr][ColumnNameLength[ctr]] = '\0'
添加尾随空字节。malloc
returnins NULL
。fread
返回长度以外的其他内容。答案 1 :(得分:1)
我在您的代码中看到的第一个错误是使用&lt; =而不是&lt; ,你有ColumnNameLength
个字符可以覆盖,因此从索引0到索引ColumnNameLength -1
。
对我来说,使用指针指针而不是使用char数组来保存字符串是很奇怪的。
答案 2 :(得分:0)
char *ColumnNameLength = (char *) malloc(Repetitions * sizeof(char));
char *DataTypeLength = (char *) malloc(Repetitions * sizeof(char));
char **ColumnName = (char **) malloc(Repetitions * sizeof(char*));
char **DataType = (char **) malloc(Repetitions * sizeof(char*));
for (int ctr = 0; ctr <= Repetitions ; ColumnNameLength[ctr] = DataTypeLength[ctr] = NULL, ctr++)
;
for (int ctr = 0; ctr <= Repetitions ; ColumnName[ctr] = DataType[ctr] = NULL, ctr++)
;
for (int ctr = 0; ctr <= FieldCount; ctr++)
{
fread((ColumnNameLength + ctr), sizeof(char), 1, pInfile);
ColumnName[ctr] = (char *) malloc((ColumnNameLength[ctr]+1) * sizeof(char));
fread(ColumnName[ctr], sizeof(char), ColumnNameLength[ctr], pInfile);
//I should add '\0' at the end of each read string, but no idea how
ColumnName[ctr][ColumnNameLength[ctr]] = '\0';
fread((DataTypeLength + ctr), sizeof(char), 1, pInfile);
DataType[ctr] = (char *) malloc((DataTypeLength[ctr]+1) * sizeof(char));
fread(DataType[ctr], sizeof(char), DataTypeLength[ctr], pInfile);
//I should add '\0' at the end of each read string, but no idea how
DataType[ctr][DataTypeLength[ctr]] = '\0';
}