Little exercise to test yor skills with C structs
- 1) From the C statement
A[j].data[k] = 63;
What do we know about the types of
j
k
data
A
- 2) Write a definition for A which will make the statement syntactically acceptable.
- 3) Write a function to fill your version of A with a different value in every cell.
Possible Solution
- 1)
j int
k int
data int *
A pointer to a structure TCell (see below)
- 2)
typedef struct TCell *Array;
struct TCell{
int * data;
}
Array A;
- 3)
typedef struct TCell *Array;
struct TCell{
int * data;
}
int main(){
int arrayDim = 10;
int dataDim = 5;
Array A = (Array)malloc(sizeof(struct TCell)*10);
int * data = (int *)malloc(sizeof(int)*dataDim);
for(int j=0; j < arrayDim; j++){
A[j].data = (int *)malloc(sizeof(int)*dataDim);
for( int k = 0; k < dataDim; k++){
A[j].data[k] = rand()%100;
}
}
}
Exercise from: CS3008
No comments:
Post a Comment