[英]Last element of 2D array of strings overwriting previous array elements
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]);
}
}
Above code is displaying last element of str2D
overwriting all of the previous array contents. 上面的代码显示了
str2D
最后一个元素, str2D
元素将覆盖所有先前的数组内容。 I need to copy sChar
to 2-D array of strings. 我需要将
sChar
复制到字符串的二维数组。
Short Answer: 简短答案:
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
. 你是不是复制内容到由指向的内存位置
str2D[row][col]
你要做的仅仅是将指针指向sChar
。 Thus, whatever is the latest content of the sChar
, is being shown. 因此,无论
sChar
的最新内容是什么,都将显示出来。
Long answer: 长答案:
You have other issues. 您还有其他问题。 First,
第一,
{{ "NULL" }};
is not the same as {{ NULL }};
{{ NULL }};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.