Question
Im given an file with an 2d array of values(topo983by450.txt) and I need to to read the name of a data le from the command
Im given an file with an 2d array of values(topo983by450.txt) and I need to to read the name of a data le from the command line, open the le, determine the size of the array required, then dynamically allocate both the 2d array topography[][] and the 1d array sumList[]. I having trouble figuring out how to use malloc to get my 2d array values to put it into calc sums. to calculate my values
void calcSums(int** topog, int* sumList ); int **malloc2d(int r, int c); int x; //a global variable
int main(int argc, char* argv[]) { /int** topography = malloc2d(ROWS ,COLS);
int count= 0; int ** a; //a is a[][], a 2d array int r,c; a = malloc2d(x,y);
char lineRead[100]; int ivalRead; double dvalRead; // file to be read must be in project directory FILE* inFile = fopen("topo983by450.txt", "r"); //open a file from user for reading
if( inFile == NULL) // should print out a reasonable message of failure here { printf("no bueno "); exit(1); }
while( fscanf(inFile,"%d",&ivalRead, &count) != EOF ){ fscanf(inFile,"%d",&ivalRead); // printf("I just read: %d ", ivalRead); } printf("done. Last value read was %d ", ivalRead); system("pause");
/* while( fgets(lineRead, 1000, inFile) != NULL) //store line just read as string "lineRead" printf("I just read the line: %s", lineRead); */ fclose(inFile);
return 0; }
int** malloc2d(int r, int c) { int i; int** t = malloc(r * sizeof(int*)); for (i = 0; i < r; i++) t[i] = malloc(c * sizeof(int)); return t; }
void calcSums(int** topog, int* sumList) { int i,j, sum, sum2, sum3, row; for( i=0; i { row = i; for (j= 0; j< COLS-1; j++) { sum = abs(topog[row][j]- topog[row][j+1]); // if out of bounds if(row-1 < 0) { sum2 = 1000000; } else { sum2 = abs(topog[row][j]- topog[row-1][j+1]); } // if out of bounds if(row+1 >= ROWS) { sum3 = 1000000; } else { sum3 = abs(topog[row][j]-topog[row+1][j+1]); }
if (sum <= sum2 && sum<= sum3) { sums[i] += sum;
} if (sum2 < sum && sum2 < sum3) { sums[i] += sum2; row--; } if (sum3 < sum&& sum3< sum2) { sums[i] += sum3; row++; } else if(sum2==sum3) // random func { sums[i] += sum3; srand(time(0)); int random = rand()%2; if(random==0) { row--; } else { row++; } } } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started