我正在尝试学习C。我想从文件中获取的1D数组填充2D数组。
现在,我正在尝试将数组指针(输出:Hello,My,name,is,Ram。)的元素带入称为单词的二维数组中。目的是删除逗号并突出显示不同行中的每个单词。我也已经实现了,但是我的输出变得有些混乱。我检查了我的输入项,发现第一行(Hello,My,name,is,Ram。)存储在word []的第1至第5行中。但是,下一行(I,own,20,数千,bucks。)从我不明白为什么的单词的行[10]开始?再加上我的输出看起来很奇怪,但包含一些未知值。请告知我该怎么做才能更正我的输出并将2D数组的大小设置为等于它包含的值
这是我的代码:
int main(int argc, const char * argv[]) {
// insert code here...
FILE *fp;
char (*points)[50];
char *array;
int width=20,height=50;
char *word;
char words [width][height];
int counter=0; // To traverse through array and tracks the current position in array.
points = malloc(sizeof(*points) * 2);
word=malloc(width*height*sizeof(char));
if (points == NULL) {
perror("malloc");
exit(0);
}
fp = fopen("/Users/shubhamsharma/Desktop/data.txt", "r");
if (fp == NULL) {
perror("fopen");
exit(EXIT_FAILURE);
}
fgets(points[0], sizeof(*points), fp);
fgets(points[1], sizeof(*points), fp);
array=points[0];
printf("%s", points[0]);
printf("%s", points[1]);
for(int i=0;i<width;i++)
{
for(int j=0,p=counter;j<height;j++,p++)
{
if(array[p]==','||array[p]=='\0')
{
words[i][j]='\n';
counter=++p;
break;
}
else
words[i][j]=array[p];
}}
printf("\n%c",words[16][0]);
for (int i=0; i<width; i++) {
for (int j=0; j<height; j++) {
if(words[i][j]=='\n')
{
break;
}
printf("\nPrinting element in word\n");
printf("%c",words[i][j]);
}
}
printf("\n");
fclose(fp);
free(points);
return 0;
return 0;
}
输出:
> Hello,My,name,is,Ram. I,own,20,thousand,bucks. Printing element in word
> HelloMynameisRam.+̮\213\377\310`\267t\377̮\213\377Iown20thousandbucks.
> Program ended with exit code: 0
我文件中的行看起来像.-
Hello,My,name,is,Ram.
I,own,20,thousand,bucks.
最佳答案
您的代码缺少#include <stdio.h>
和#include <stdlib.h>
。
之后,您的代码将正确分配内存;但是您绝不使用word
,因此可以将其删除。
您的代码正确读取第一行。但是,在条件array[p] == '\0'
之后,下一次进入j
循环时,在points[0]
读取的数据结束之后,它只会继续从fgets
读取垃圾。这会导致不确定的行为,您很幸运,结果与以前一样连贯。
对于array[p] == '\0'
情况,您需要有其他代码才能将array
移至阅读下一行的位置,例如array = points[1]; p = counter = 0; break;
。 (实际上p
在此循环中是多余的,您可以直接使用counter
)
这将涉及一个额外的变量,以跟踪您要使用的points
索引,并确保您不会结束。
更好的方法是在处理时仅读取每一行:摆脱array
,只有一个缓冲区char line[50];
,并在开始时调用fgets
,然后每次到达'\0'
在处理那条线。
(您的整个算法可能会有很大的改进,但是我会留给您:学习的一部分是按照您的想法做事,看看最终的利弊,然后尝试改进自行决定)。
最后,您用于显示字符串的代码是错误的。根据输入文件的不同,words[16][0]
可能会超出您阅读内容的结尾,并且当前您在每个字符之前打印Printing element in word
。您在问题中发布的示例输出未显示此内容,因此我想您发布的代码与您正在测试的代码不匹配。
相反,我建议您更新“读取”代码以对字符串进行空终止(使用words[i][j]='\0';
而不是words[i][j]='\n';
),然后可以使用标准函数来打印它们:
for (int n = 0; n < i; n++)
printf("%s\n", words[n]);
Here是您的代码在我建议的最小改动下工作。我放入了一些调试
printf
行,您可以对其进行注释以查看其工作方式,然后改为使用stdin
而不是打开文件,以便可以在联机编译器中看到它的运行。您仍然可以做很多事情来改善您的代码! (首先,请处理\n
留在缓冲区中的多余fgets
)。
关于c - 从C中的1D数组填充2D数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32814447/