c - 与 malloc 相关的逻辑错误

标签 c malloc

这是我写的代码。我有一些逻辑错误。

typedef struct bigint_ {

int signbit;
int*ptr;

} bigint;
void print_bigint(bigint big_num);
bigint shift_by_power_of_10(bigint big_num, int d);

main()
{
bigint a;
bigint b;
a.ptr=malloc(6*sizeof(int));
a.ptr[0] = 1;
a.ptr[1] = 2;
a.ptr[2] = 2;
a.ptr[3] = 2;
a.signbit = 0;
b=shift_by_power_of_10(a,3);
print_bigint(b);

}
bigint shift_by_power_of_10(bigint big_num, int d)
{
int len = (int)(sizeof(big_num.ptr)/sizeof(int));
printf("%d\n",len);
big_num.ptr = realloc(big_num.ptr,d*sizeof(int));
int i;
for (i=len;i<len+d;i++)
{
    big_num.ptr[i] = 0;
}
return(big_num);

}
void print_bigint(bigint big_num)
{
int i;
if (big_num.signbit == 1)
{
    printf("-");
}
int len = (int)(sizeof(big_num.ptr)/sizeof(int));
for (i=0;i<len;i++)
{
    if (i!=len-1)
    {
        printf("%d",big_num.ptr[i]);
    }
     else
    {
            printf("%d\n",big_num.ptr[i]);
    }
}   
}

在函数中shift_by_power_of_10()打印时len ,我应该得到 4,但我得到的 len 为 2。

请指出其中的逻辑错误。

最佳答案

sizeof(big_num.ptr) 在 x86 上等于 4(在 x64 上等于 8),因为它是指针的大小。 sizeof(int) 等于 4 (VS2010),这就是为什么我会得到 4/4 = 1(在 x86 上运行):

int len = (int)(sizeof(big_num.ptr)/sizeof(int));

如果你在 x64 上运行它,那么你可以获得 8/4 = 2

关于c - 与 malloc 相关的逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25340285/

相关文章:

c++ - 错误: ‘calloc’ was not declared in this scope

ios - 如何解决malloc_error_break?

c - 如何在C中存储事先不知道大小的数字序列?

c - malloc() 并分配 : C code in run well in OS X; not in Win 8. 1

c++ - GPC 多边形裁剪器是否进行三角测量?

c - C中的共享库

c - Visual Studio 2010 在程序结束后退出

c - 存储在 C 结构 'magically' 中的值会自行更改

c - 在内存中排序值时重新分配的最有效方法?

c - 释放一棵特里树