具有结构的C指针数学 [英] C pointer math with structures

查看:59
本文介绍了具有结构的C指针数学的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了更好地学习指针数学,我编写了这段代码.目的是增加将指针扔到结构上并打印其成员的指针.我知道如何打印它的成员更简单的方法,但我真的很想知道如何弄乱我的指针数学.谢谢.

Trying to learn pointer math better I wrote this code. The intention was to increment the pointer threw the structure and print it's members. I know how to print it's member easier ways but would really like to know how my pointer math is messed up. Thank you.

typedef struct{ 
  int num;
  int num2;
  char *string;
} astruct ;

int main (int argc, const char * argv[])
{
  astruct mystruct = { 1234, 4567,"aaaaaaa"};

  astruct *address;
  address = &mystruct;

  // this does print 1234
  printf("address 0x%x has value of:%i\n",address, *address); 
  address = address + sizeof(int);

  //this does NOT print 4567
  printf("address 0x%x has value of:%i\n",address, *address); 
  address = address + sizeof(int);

  //this crashes the program, I wanted to print aaaaaaaa
  printf("address 0x%x has value of:%s\n",address, **address); 

  return 0;
}

推荐答案

指针算术将指针增加所指向的字节数.例如,

Pointer arithmetic increments a pointer by the number of bytes pointed to. For example,

int a[2];
int *p = a;

assert( &a[0] == p )
assert( &a[1] == p + 1 )

因此,您的电话

address = address + sizeof(int);

实际上将address更改为address + sizeof(int) * sizeof(astruct)(使用常规而非指针算术).

actually changes address to address + sizeof(int) * sizeof(astruct) (using normal, not pointer arithmetic).

没有保证的方法可以完成您尝试做的事情,因为允许编译器在结构中引入填充.考虑结构

There is no guaranteed way to do what you are trying, because the compiler is allowed to introduce padding in a struct. Consider the struct

struct A {
    char a;
    int b;
};

编译器很可能为该结构提供以下布局:

The compiler will most likely give this struct the following layout:

+------------+-------------------+-------------+
| a (1 byte) | (3 bytes padding) | b (4 bytes) |
+------------+-------------------+-------------+

因此,您无法通过获取结构实例的地址并添加1来进入b.

So you cannot get to b by taking the address of a struct instance and adding 1.

在特定于 的情况下,编译器可能不会引入填充,因此您可以使用这些行来更新address:

In your specific case, the compiler probably doesn't introduce padding, so you may be able to use these lines to update address:

address = (char *) address + sizeof(int); // OR...
address = (int *) address + 1;

不过,这再次完全取决于编译器以您认为的方式布局该结构,任何小的更改都可能破坏它,因此您确实不应依赖这种类型的行为.

Again, though, this depends entirely on the compiler laying out the struct the way you think it will, and any small change will probably break it, so you really shouldn't rely on this type of behavior.

这篇关于具有结构的C指针数学的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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