gpt4 book ai didi

c - 将一个表放入内存

转载 作者:太空宇宙 更新时间:2023-11-04 07:20:29 25 4
gpt4 key购买 nike

我必须从 txt 文件中读取一个表格,并且我必须将值写入内存。

我能够从文件中读取数据(逐行)并将它们放入变量(使用 sscanf),但我不知道如何创建和填充“字符串”数组。

我需要创建一个包含 n 行和 9 列字符串/字符的数组。

这段代码给了我一个编译器警告(“警告:传递'strcpy'的参数1使指针来自整数而不进行强制转换”)和程序错误:

    char matrix_model_data[3][10];
strcpy(matrix_model_data[0][0],"some text");
printf("VALUE = %s\n",matrix_model_data[0][0]);

我该怎么办?

谢谢

编辑

现在我已经使用我的值修改了代码,但它只打印最后一条记录 1317 次 (mdata_num = 1317)...为什么?

    char ***table = (char ***) calloc(mdata_num, sizeof(char**));

int i, j, m;
for(i=0; i<mdata_num; i++)
{
fgets(LineIn,500,fIn);
sscanf(LineIn, "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s",stTemp0,stTemp1,stTemp2,stTemp3,stTemp4,stTemp5,stTemp6,stTemp7,stTemp8);
iterazioni++;
table[i] = calloc(COLUMNS, sizeof(char*));
for(j=0; j<COLUMNS; j++)
{

table[i][j] = calloc(MAX_STRING_SIZE, sizeof(char));
}
table[i][0] = stTemp0;
table[i][1] = stTemp1;
table[i][2] = stTemp2;
table[i][3] = stTemp3;
table[i][4] = stTemp4;
table[i][5] = stTemp5;
table[i][6] = stTemp6;
table[i][7] = stTemp7;
table[i][8] = stTemp8;
}

for(i=0; i<mdata_num; i++)
{
for(j=0; j<COLUMNS; j++)
{
printf("%s\t", table[i][j]);
}
printf("\n");
}

//FREE THE TABLE
for(i=0; i<mdata_num; i++)
{
for(j=0; j<COLUMNS; j++)
{
free(table[i][j]);
}
free(table[i]);
}
free(table);

最佳答案

有两种方式,静态或动态。使用哪一个取决于您是否知道行数。

静态

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

#define ROWS 10
#define COLUMNS 9
#define MAX_STRING_SIZE 256

int main(){

char table[ROWS][COLUMNS][MAX_STRING_SIZE];

//EXAMPLE OF USE
for(i=0; i<ROWS; i++)
for(j=0; j<COLUMNS; j++)
strcpy(table[i][j], "hi");

}

动态

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

#define ROWS 10
#define COLUMNS 9
#define MAX_STRING_SIZE 256

int main(){

char ***table = calloc(ROWS, sizeof(char**));

int i, j;
for(i=0; i<ROWS; i++){
table[i] = calloc(COLUMNS, sizeof(char*));
for(j=0; j<COLUMNS; j++){
table[i][j] = calloc(MAX_STRING_SIZE, sizeof(char));
}
}

//FREE THE TABLE
for(i=0; i<ROWS; i++){
for(j=0; j<COLUMNS; j++){
fprintf(stderr, "%s, ", table[i][j]);
free(table[i][j]);
}
fprintf(stderr, "\n");
free(table[i]);
}
free(table);

}

当然,您需要检查 calloc 调用是否返回 NULL。使用 calloc 分配字符串确保字符串将被初始化为零。该算法将创建 10 行,其中 9 列是每列 256 个字符的字符串。

关于c - 将一个表放入内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21931618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com