这是我写的代码。我有一些逻辑错误。
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.
请指出其中的逻辑错误。
答案 0 :(得分:0)
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