【问题标题】:I can't understand why i have the wrong size of my array我不明白为什么我的数组大小错误
【发布时间】:2016-04-20 01:58:51
【问题描述】:

我对这个 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);
}

【问题讨论】:

标签: c arrays pointers sizeof


【解决方案1】:

首先,数组不是指针,反之亦然。

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

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

如果您有一个正确以 null 结尾的 char 数组,您可以使用 strlen() 来获取字符串元素的长度,但是,这仍然可能无法为您提供 实际 em> 分配的内存大小,无论如何。您需要自己跟踪大小。通常,您不能期望从指针本身提取信息。

【讨论】:

  • 感谢您的解释,您现在可以帮我了解我应该使用的语法来获得好的结果吗?因为我实际上同意它是一个指针,但是如何使用一元 (*) 仍然不能解决我的问题。
  • @franckstifler 你说的是哪个一元*,好吗?
  • strlen 肯定不会给你分配的大小,至少是strlen(...) + 1
  • 对不起我的英语,我不是以英语为母语的人。刚刚对strlen() 感到困惑,它不适合字符串吗?我的程序旨在用整数数组模拟整数堆栈。我希望我的用户应该选择堆栈的大小,并在我的指针 int* tab 上分配内存。
  • @franckstifler 就是这样,分配很好,只是不要指望sizeof 会给你大小,它不会。就是这样
猜你喜欢
  • 1970-01-01
  • 2020-04-20
  • 2020-06-15
  • 1970-01-01
  • 1970-01-01
  • 2022-12-18
  • 1970-01-01
  • 2023-03-28
  • 2021-04-28
相关资源
最近更新 更多