2D字符串数组的最后一个元素覆盖先前的数组元素 [英] Last element of 2D array of strings overwriting previous array elements
本文介绍了2D字符串数组的最后一个元素覆盖先前的数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
void read_char_from_file(FILE *fp, int formatted)
{
char sChar[16], eol;
int col=0, row=0,ind=0,count=0;
char *str2D[4][4]={{ "NULL" }};
while ( (fscanf(fp, "%s%c", sChar,&eol)) != EOF)
{
if(eol!='\n')
{
str2D[row][col]=sChar;
printf("Row: %d, Col: %d = %s\n",row, col,str2D[row][col]);
col++;
}
else {
str2D[row][col]=sChar;
printf("Row: %d, Col: %d = %s\n",row, col,str2D[row][col]);
row++;
col=0;
}
str2D[row][col]=0;
}
int i,j;
for (i=0; i < 3; i++)
{
for(j=0; j <3; j++)
printf("%s",str2D[i][j]);
}
}
以上代码显示了str2D
的最后一个元素,覆盖了所有先前的数组内容.我需要将sChar
复制到二维字符串数组中.
Above code is displaying last element of str2D
overwriting all of the previous array contents. I need to copy sChar
to 2-D array of strings.
推荐答案
简短答案:
您不将内容复制到由str2D[row][col]
指向的存储位置,只是将指针指向sChar
.因此,无论sChar
的最新内容是什么,都将显示出来.
You are not copying the content into the memory location pointed to by str2D[row][col]
, you're just making the pointer point to sChar
. Thus, whatever is the latest content of the sChar
, is being shown.
长答案:
您还有其他问题.首先,
You have other issues. First,
-
{{ "NULL" }};
与{{ NULL }};
不同
- 您正在创建一个二维指针数组.在将任何内容存储在指针指向的那些存储位置之前,需要确保它们指向一些有效的位置.
{{ "NULL" }};
is not the same as{{ NULL }};
- You are creating a 2-D array of pointers. Before you can store anything in those memory locations pointed to by the pointers, you need to make sure that they point to some valid locations.
这篇关于2D字符串数组的最后一个元素覆盖先前的数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文