C 尝试将文件读入动态分配的2d数组
我试图将一个文件读入一个动态分配的2d数组中,但我总是打印出相同的行。我放在这段代码中的文件是一个.txt文件,有1000行。最后的打印是检查数组是否获得了正确的数据。最后,我正在尝试realloc,因为代码将适合放入数组的行数。谢谢:)C 尝试将文件读入动态分配的2d数组,c,arrays,dynamic,2d,allocation,C,Arrays,Dynamic,2d,Allocation,我试图将一个文件读入一个动态分配的2d数组中,但我总是打印出相同的行。我放在这段代码中的文件是一个.txt文件,有1000行。最后的打印是检查数组是否获得了正确的数据。最后,我正在尝试realloc,因为代码将适合放入数组的行数。谢谢:) #包括 #包括 #包括 内部主(空) { 字符缓冲区[349]; char*del=”“; int i=0; 整数计数=0; int len=100; int行=10; int max=10; 字符**d; d=malloc(行*大小)(字符*); 对于(i=
#包括
#包括
#包括
内部主(空)
{
字符缓冲区[349];
char*del=”“;
int i=0;
整数计数=0;
int len=100;
int行=10;
int max=10;
字符**d;
d=malloc(行*大小)(字符*);
对于(i=0;i
for(i=max;id
看起来不像任何东西的“2D数组”。数组是连续的。您的分配不是连续的。我建议您更改d
的类型并避免过度分配
char (*d)[349] = NULL;
size_t d_size = 0;
检查d_size
是否为二进制幂次方(幂次为2
),以确定何时调整大小,并通过加倍调整大小:
if ((d_size & (d_size + 1)) == 0) {
void *temp = realloc(d, (2 * d_size + 1) * sizeof *d);
if (temp == NULL) {
perror(realloc);
exit(EXIT_FAILURE);
}
d = temp;
}
由于d
以NULL
和d\u size
二进制幂(0
)开始,因此需要在分配之前进行容量检查。因此,您可以消除缓冲区
无需存储d
的容量,因为我们知道它将是通过反复增加d\u大小
获得的第一个二进制幂。d\u大小
将成为您的i
,如果您愿意的话
除此之外,BLUEPIXY在评论中为您的问题提供了解决方案。经过一次更正,这些问题是:
strcpy(d[i],缓冲区);
d=realloc(d,sizeof(*d)*max*2);
for(int j=max;j
printf(“%zu\n”,strlen(d[i]);
至少这四项是让你的程序正常运行所必需的(无论这意味着什么),但你也应该考虑这两项:
- 当
d=realloc(d,…);
失败并返回NULL
时,您以前的d
值会发生什么变化?它会泄漏到空气中。您应该将d
的返回值存储到temp
变量(如下面)中,并在继续之前检查NULL
- 不要忘了释放你所有的内存
将其中少数几个仍然适用于我迄今所学的内容整合到一起:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char (*d)[349] = NULL;
size_t d_size = 0;
for (;;)
{
if ((d_size & (d_size + 1)) == 0)
{
void *temp = realloc(d, (2 * d_size + 1) * sizeof *d);
if (temp == NULL)
{
break;
}
d = temp;
}
if (fgets(d[d_size], sizeof d[d_size], stdin) == NULL) {
break;
}
d_size++;
}
for (size_t i = 0; i < d_size; i++)
{
printf("%s\n", d[i]);
printf("%zu\n", strlen(d[i]));
}
free(d);
}
#包括
#包括
#包括
内部主(空)
{
char(*d)[349]=NULL;
尺寸d尺寸=0;
对于(;;)
{
如果((d_大小和(d_大小+1))==0)
{
void*temp=realloc(d,(2*d_尺寸+1)*sizeof*d);
if(temp==NULL)
{
打破
}
d=温度;
}
if(fgets(d[d_size],sizeof d[d_size],stdin)==NULL){
打破
}
d_size++;
}
对于(大小i=0;i
1)d[i]=buffer;
更改为strcpy(d[i],buffer);
2)d=realloc(d,sizeof(d)**2);
d=realloc(d,sizeof(*d)**max*2);
3i=max;ii=max;i4
printf
5)此部分i
到其他变量for(int j=max;j
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char (*d)[349] = NULL;
size_t d_size = 0;
for (;;)
{
if ((d_size & (d_size + 1)) == 0)
{
void *temp = realloc(d, (2 * d_size + 1) * sizeof *d);
if (temp == NULL)
{
break;
}
d = temp;
}
if (fgets(d[d_size], sizeof d[d_size], stdin) == NULL) {
break;
}
d_size++;
}
for (size_t i = 0; i < d_size; i++)
{
printf("%s\n", d[i]);
printf("%zu\n", strlen(d[i]));
}
free(d);
}