C将元素放在不带括号的位置 [英] C get element on place without parenthesis

查看:70
本文介绍了C将元素放在不带括号的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了数组:

int main()
{
    int num[3] = {1, 2, 3}
    return 0;
}

我想将元素放置到位1。

I want to get element in place 1.

为什么不能通过此代码获取元素?

Why can not I get the element by this code?

printf("%d", *(num + (sizeof(int)*1)));

这有什么不同?

printf("%d", *(num + 1));


推荐答案

我了解您认为使用<$ c来增加指针$ c> sizeof(int)将带您到数组中的下一个成员。但是,这不是它的工作方式:

I understand you thought incrementing the pointer using sizeof(int) will get you to the next member in the array. However, this is not how it works:

在您编写时:

printf("%d", *(num + 1));

指针前进到数组中的下一个成员(它是一个int指针,因此当您递增时它会提高sizeof(int)(通常为4)字节)。但是当您写时:

the pointer advances to the next member in the array (it is an int pointer and therefore when you increment it, it advances sizeof(int) (which is usually 4) bytes). But when you write:

printf("%d", *(num + (sizeof(int)*1)));

您尝试将指针前进4个成员(或4 * sizeof(int)个字节),其中不在阵列的边界内。

you try to advance the pointer by 4 members (or 4*sizeof(int) bytes), which is out of the boundaries of your array.

这篇关于C将元素放在不带括号的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆