I have a struct with an int array inside that I'm passing to a function for the array to be initialized
array struct like so..
typedef struct Container{
struct intArray *P;
int length;
} Container;
typedef struct intArray{
int *array;
int length;
} intArray;
function to initialize the array like so...
int Initializer(intArray *myStruct, int n)
{
myStruct->array = malloc(sizeof(int) * (lengthOfint);
^
If n=55 then length would be 2
//let's just say n=5
myStruct->array[0] = n;
//return 1 if successful
return 1;
}
In another function I am calling the initializer function like so...
Container *myContainer = malloc(sizeof(Container));
myContainer->P = malloc(sizeof(intArray *) * Some_Defined_Value);
Initializer(&myContainer, 5);
printf("the data that should be at index 0 -> %d\n", myContainer->P.array[0];
I would think that the printf statement would print out 5 but it prints out garbage of varying numbers every time I compile it. I don't think I have a grasp of the array within a struct within a struct idea.
myStruct->array = malloc(sizeof(int) * (lengthOfint);
is missing a close parenthesis. Also, I'm puzzled hown=55
leads tolengthOfint == 2
; are you measuring in bits and assumingsizeof(int) == 4
andCHAR_BIT == 8
? Not unreasonable assumptions, but the use of a bit count is not so obvious. – Jonathan Leffler Jun 12 '13 at 23:37lengthOfint == ceil(log10(abs(n)))
. – David Foerster Jun 12 '13 at 23:46