相关疑难解决方法(0)

如何找到'sizeof'(指向数组的指针)?

首先,这里是一些代码:

int main() 
{
    int days[] = {1,2,3,4,5};
    int *ptr = days;
    printf("%u\n", sizeof(days));
    printf("%u\n", sizeof(ptr));

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

有没有办法找出ptr指向的数组的大小(而不是仅仅给出它的大小,在32位系统上是4个字节)?

c arrays pointers sizeof

288
推荐指数
8
解决办法
35万
查看次数

在C中,sizeof运算符在传递2.5m时返回8个字节,在传递1.25m*2时返回4个字节

我不明白为什么sizeof运营商产生以下结果:

sizeof( 2500000000 ) // => 8 (8 bytes).
Run Code Online (Sandbox Code Playgroud)

...它返回8,当我执行以下操作时:

sizeof( 1250000000 * 2 ) // => 4 (4 bytes).
Run Code Online (Sandbox Code Playgroud)

...它返回4而不是8(这是我的预期).有人可以澄清如何sizeof确定表达式(或数据类型)的大小以及为什么在我的特定情况下会发生这种情况?

我最好的猜测是sizeof运算符是编译时运算符.

赏金问题:是否有运行时运算符可以评估这些表达式并产生我的预期输出(没有强制转换)?

c sizeof

65
推荐指数
3
解决办法
3597
查看次数

sizeof如何知道数组的大小?

我的代码如下:

main() {
    int array[5] = {3,6,9,-8,1};
    printf("the size of the array is %d\n", sizeof(array));
    printf("the address of array is %p\n", array);
    printf("the address of array is %p\n", &array);
    int * x = array;
    printf("the address of x is %p\n", x);
    printf("the size of x is %d\n", sizeof(x));
}
Run Code Online (Sandbox Code Playgroud)

输出是

the size of the array is 20
the address of array is 0x7fff02309560
the address of array is 0x7fff02309560
the address of x is 0x7fff02309560
the size of x is …
Run Code Online (Sandbox Code Playgroud)

c c++ arrays pointers

15
推荐指数
4
解决办法
4657
查看次数

C int数组和指针交互

以下代码......

int array[] = {17, 18, 19};
printf("Location of array: %p\n",       array);
printf("   Value of array: %d\n",       *array);
printf("    Size of array: %d bytes\n", sizeof(array));
Run Code Online (Sandbox Code Playgroud)

产生输出

Location of array: 0x7ffd0491c574
   Value of array: 17
    Size of array: 12 bytes
Run Code Online (Sandbox Code Playgroud)

当我在第二行使用变量数组时,它指的是"17"的位置.当我在第三个上使用它时,它取消引用指针并打印出数字17.这些,我理解.

在最后一行,它打印出"12字节"作为数组的大小.为什么不打印出4个字节,因为在前两个使用同一个变量时,它似乎只能引用数组的零索引?如何sizeof知道查看数组的其余部分,而不是只打印4个字节(就像我运行时那样(sizeof(*array))?

c arrays pointers

1
推荐指数
1
解决办法
197
查看次数

C++ 为什么数组没有长度属性

假设我们有一个数组

int arr[3];
Run Code Online (Sandbox Code Playgroud)

在C++11中我们可以做

end(arr);
Run Code Online (Sandbox Code Playgroud)

得到 arr 的边界。

sizeof(arr)/sizeof(arr[0])
Run Code Online (Sandbox Code Playgroud)

可以得到数组的大小。

实际上,我来自 Java,并且是 C++ 新手,拥有某些东西很直观。就像arr.length,但是为什么 C++ 没有这个好功能呢?使用外部函数来获取数组的大小是很奇怪的。(C++11之后甚至添加了结束函数,在此之前事情更麻烦)我猜它有什么。为了处理数组后面的实现,必须有一些边界标记,就像字符串末尾的“\0”一样。那么为什么不更进一步去获得某物呢?像arr.length?

c++ arrays

1
推荐指数
1
解决办法
2717
查看次数

标签 统计

arrays ×4

c ×4

pointers ×3

c++ ×2

sizeof ×2