我不明白为什么我的数组大小错误

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

我对这个 C 程序有疑问。我不明白为什么即使我用 malloc() 指令初始化我的数组,但无论我传递给函数初始化的第二个参数是什么,我的大小都是相同的(4 字节)。

#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);
}

首先,数组不是指针,而是vice-versa.

在您的代码中,S.tab 是一个指针,在指针上使用 sizeof 将评估指针本身的大小,而不是分配给该指针的内存量。

在您的平台上,指针 (int *) 的大小为 4 个字节,因此您看到的输出始终为 4。

如果你有一个正确的 null-terminated char 数组,你可以使用 strlen() 来获取字符串元素的长度,但是,仍然可能无法给出无论如何,您 actual 分配的内存大小。您需要自己跟踪尺寸。通常,您不能指望从指针本身提取信息。