I'm trying to implement Array ADT in C:
#include <stdio.h>
#include <stdlib.h>
#define sizeArr 20
struct array{
int* A;
int size; //size is the actual size of A
int length; //length are the positions actually being used in A,from A[0] to A[length-1]
};
void fillArray( struct array* arr ){
printf( "Number of elements in array (max. %i): ", arr->size );
scanf( "%i", &arr->length );
if( arr->length <= arr->size ){
for ( int i = 0; i < arr->length; i++ ){
printf( "arr[%i] := ", i );
scanf( "%i", &arr->A[i] );
}
}else
exit(1);
}
void displayArray( struct array* arr ){
for ( int i = 0; i < arr->length; i++ )
printf( "%i\n", arr->A[i] );
}
void appendArray( struct array* arr, int element ){
if( arr->length < arr->size )
arr->A[arr->length++] = element;
else
exit(1);
}
int main( void ){
struct array arr = { .size = sizeArr, .A = ( int* ) malloc( arr.size*sizeof(int) ), .length = 0 };
fillArray( &arr );
printf("%i", arr.size);
displayArray( &arr );
appendArray( &arr, 41 );
printf("--------\n");
displayArray( &arr );
free( arr.A );
return 0;
}
When I choose arr.length = 7
I get this; works properly.
When I choose arr.length = 8
I get this; You can see that instead of appending 41
, it does so with some other random number, probably garbage.
When I choose arr.length = 16
I get this; You can appreciate that 41
is succesfully apended, but positions 8, 9, 10, exclusively, print garbage instead of the values they were asigned; all other array positions are printed properly.
I've been wrapping my head around this for a few hours, however I don't know whats wrong with the code; the only problems that I think could lead to this are:
arr.A
is not actually being given arr.size
as its size.
displayArray()
is priting this positions wrongly, but the correct numbers are there
appendArray()
and fillArray()
have some kind of issue whe inserting elements in this positions.
If y'all could help me sorting out this issue, I'd really appreciate it.
Thanks in Advance.
You cannot refer to a previous member of a struct within the initialization. Use sizeArr instead:
struct array arr = {
malloc(sizeArr*sizeof(int)),
sizeArr,
0
};
Or even better write a function to create an array. malloc()
may fail so it's a good idea to implement error checks.