added constructor function

This commit is contained in:
2026-05-30 19:45:30 +02:00
parent c737f8ab0f
commit 2a3cb53aa1
+15 -5
View File
@@ -10,22 +10,32 @@ struct IntArray{
void readintarray(struct IntArray *input) { void readintarray(struct IntArray *input) {
printf("inputlength:%zu\n", input->length); printf("inputlength:%zu\n", input->length);
for (int i = 0; i < input->length; i++) { for (size_t i = 0; i < input->length; i++) {
printf("digit:%d = %d\n", i, input->data[i]); printf("digit:%d = %d\n", i, input->data[i]);
} }
} }
struct IntArray *create_int_array(size_t length) {
struct IntArray *myintarray = malloc(sizeof(struct IntArray)); /* allocate memory for struct */
myintarray->data = malloc(sizeof(int) * length); /* make sure the pointer in the struct points to the array */
myintarray->length = length; //forgot to actually assign a value to the struct
if (myintarray->data == NULL) {
exit(0);
}
return myintarray;
}
int main() { int main() {
srand(time(NULL)); srand(time(NULL));
printf("how many numbers?\n"); printf("how many numbers?\n");
int length; int length;
scanf("%d", &length); scanf("%d", &length);
struct IntArray *myintarray = malloc(sizeof(struct IntArray)); /* allocate memory for struct */ struct IntArray *myintarray = create_int_array(length);
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++) { for (int i = 0; i < length; i++) {
myintarray->data[i] = rand() % 10; myintarray->data[i] = rand() % 10;
printf("number:%d = %d\n",i,myintarray->data[i]); printf("number:%d = %d\n",i,myintarray->data[i]);