struct practice
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stddef.h>
|
||||
#include <stdlib.h>
|
||||
#include <time.h>
|
||||
struct IntArray{
|
||||
int *data;
|
||||
size_t length;
|
||||
};
|
||||
|
||||
void readintarray(struct IntArray *input) {
|
||||
printf("inputlength:%zu\n", input->length);
|
||||
for (int i = 0; i < input->length; i++) {
|
||||
printf("digit:%d = %d\n", i, input->data[i]);
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
srand(time(NULL));
|
||||
printf("how many numbers?\n");
|
||||
int length;
|
||||
scanf("%d", &length);
|
||||
|
||||
struct IntArray *myintarray = malloc(sizeof(struct IntArray)); /* allocate memory for struct */
|
||||
int *myarray = malloc(sizeof(int) * length); /* allocate memory for array that the struct points to */
|
||||
|
||||
myintarray->data = myarray; /* make sure the pointer in the struct points to the array */
|
||||
myintarray->length = length; //forgot to actually assign a value to the struct
|
||||
for (int i = 0; i < length; i++) {
|
||||
myintarray->data[i] = rand() % 10;
|
||||
printf("number:%d = %d\n",i,myintarray->data[i]);
|
||||
}
|
||||
|
||||
readintarray(myintarray);
|
||||
|
||||
free(myintarray->data);
|
||||
free(myintarray);
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user