write in programming language C, please Suppose we have the following structure
ID: 3742692 • Letter: W
Question
write in programming language C, please
Suppose we have the following structure (record) declaration. typedef struct int xi int y: myDataT Write a program that dynamically allocates a triangular-like 2D array of the above structure with the given number of rows denoted by N such that the first row (row 0) will have one record, second row (row 1) will have two records, and so on. The last row (row N-1) will have N records. For example, when N is 5, conceptually the 2D array will look like y-? y-? y-? y-? y-? y-? y-? y-? y-? y-? y-? y-? y-? After allocating then memory, your program should initialize x and y fields in each cell by setting them to corresponding cells' row numbers and column numbers, respectively. So after the initialization, the above array will look like: y-0 y-l x-2 x-2 y-2 y-2 y-2 y-3 y-0 y-I Finally, your program should free up (release) the allocated memory.Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int x;
int y;
} myDataT;
int main() {
// declaring the variables
int N, i, j;
// taking input for N
printf("Enter N: ");
scanf("%d", &N);
// allocating the space for number of rows(N)
myDataT **arr = (myDataT **)malloc(N * sizeof(myDataT *));;
// allocating the number of columns in each row
for (i = 0; i < N; i++){
arr[i] = (myDataT *)malloc((i + 1) * sizeof(myDataT));
}
// setting the value in each cell
for (i = 0; i < N; i++){
for (j = 0; j <= i; j++) {
arr[i][j].x = i;
arr[i][j].y = j;
}
}
// free all the memory
for (i = 0; i < N; i++){
free(arr[i]);
}
free(arr);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.