简体   繁体   English

2D字符串数组的最后一个元素覆盖先前的数组元素

[英]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 }};
  • 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. 在将任何内容存储在指针所指向的那些存储位置之前,需要确保它们指向一些有效的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM