How to create a 2D array

对着背影说爱祢 提交于 2021-02-11 15:14:22

问题


Im stil a beginner in C programming and I need a little help writing a code for my C programming class . The prompt is: Input for this program is a two-dimensional array of floating point data located in a file named textfile94. The input array will contain 3 rows of data with each row containing 5 columns of data.

  • I want you to use the two-subscript method of dynamic memory allocation.
  • Use malloc to create an array that holds pointers.
  • Each element of that array points at another array, which is the row of data.
  • Use malloc in a loop to create your rows.
  • Then you can use two subscript operators [r][c] to get at your data to do the summing and averaging that the program calls for.

This program calls for hard-coded height and width of the 2D array, known ahead of time (3x5, actually). Instead of writing in the literal numbers in your code, I want you to create a global constant variable to hold those dimensions, and use those in your code.

Here is what I have so far (I'm not sure if its correct):

#include <stdio.h>
#include <stdlib.h>

#define int rows = 3;
#define int columns = 5;

float array[rows][columns];

int main(int argc, char* argv[]){
FILE* fin;
float x;
int i,j;
int* array;

fin = fopen("textfile94", "r");
fscanf("%f", &x);
array = (int*) malloc(rows*sizeof(int*));

for(i=0;i<rows;i++){
   for(j=0;j<columns;j++)
   array[i]=(int*) malloc(columns* sizeof(int));
}
  }
printf("The Average values for the three rows are:%f",array[rows]);
printf("The Average values for the five columns are:%f", array[columns]);

return 0;
}

回答1:


Since you already know the dimensions of the array(3x5) you do not need to allocate it dynamically using malloc().
What you have is correct(but you should make it local instead of global):

float array[3][5];

This already allocates enough memory to hold all the array elements.

Also your requirement states:

I want you to create a global constant variable to hold those dimensions, and use those in your code.

Which means you need to declare constants to indicate array elements, something like:

const int rows = 3;
const int columns = 5;

float array[rows][columns];

EDIT:

From your comments, I believe you are using c89(or earlier version).In c99 variable length Arrays(look up VLA on google if you are not aware of this) are allowed,Which means above would compile.But in c98 VLA are not allowed. C89 and earlier versions require using compile-time constant expressions for the array dimension.So you will need to use compile-time constant expressions (which const-qualified variables are not in C). So you will need to use:

#define ROWS 3
#define COLUMNS 5

float array[ROWS][COLUMNS];


来源:https://stackoverflow.com/questions/8041273/how-to-create-a-2d-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!