franckstifler
franckstifler

Reputation: 396

I can't understand why i have the wrong size of my array

I have a problem with this C program. I don't understand why even though i initialized my array with a malloc() instruction, I am having the same size (4bytes) whatever is the second parameter i pass to my function initialize.

#include <stdio.h>
#include <stdlib.h>

typedef struct stack{
    int size;
    int *tab;
    int top;
} stack;

void initialize(stack* st, int sizeArray);
int pop(stack* stack);
void push(stack* stack, int number);


int main(){
    int sized;
    stack S;
    stack* ptr_S = &S;
    printf("Enter the size of your stack please: \n");
    scanf("%d", &sized);
    //We send the pointer of the stack to initialise
    initialize(ptr_S, sized);
    printf("%d\t%d", S.size, S.top);
    //printf("\nThe size of the array is: %d\n", sizeof(S.tab)/sizeof(int));
    printf("\nThe size of the array is: %d\n", sizeof(S.tab));
    pop(ptr_S);
    return 0;
}

void initialize(stack* st, int sizeArray){
    st->size = sizeArray;
    st->top = 0;
    st->tab = (int*)malloc(sizeof(int) * sizeArray);
}

Upvotes: 1

Views: 74

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

First of all, arrays are not pointers, ane vice-versa.

On your code, S.tab is a pointer, and using sizeof on a pointer will evaluate to the size of the pointer itself, not the amount of allocated memory to that pointer.

On your platform, a pointer (int *) is having a size of 4 bytes, so you always see the output being 4.

In case, you have a properly null-terminated char array, you can use strlen() to get the length of the elements of the string, however, still that may not give you the actual size of the memory allocated, anyway. You need to keep track of the size yourself. Normally, you cannot expect to extract the information from the pointer itself.

Upvotes: 4

Related Questions