【发布时间】:2018-05-27 01:29:35
【问题描述】:
我正在使用指向结构的指针。我想知道是否可以在不使用 ++ 运算符的情况下直接移动到特定位置。
#include <stdio.h>
#include <stdlib.h>
#define ARRAY_SIZE 10
struct dummy{
int id;
char buffer[10];
};
typedef struct dummy dummy_struct;
int main()
{
int i=0;
dummy_struct *ds = malloc(sizeof(dummy_struct)*ARRAY_SIZE);
dummy_struct *iterator = ds;
for(i=0;i<ARRAY_SIZE;i++)
{
iterator->id = i;
sprintf(iterator->buffer,"%d",i);
iterator++;
}
iterator = ds;
for(i=0;i<ARRAY_SIZE;i++)
{
printf("%d:%s:%p\n",iterator->id,iterator->buffer,iterator);
iterator++;
}
// I want to access directly to 5th position
iterator = ds + (sizeof(dummy_struct)*5);
printf("5th position %d:%s:%p\n",iterator->id,iterator->buffer,iterator);
return 0;
}
此声明
iterator = ds + (sizeof(dummy_struct)*5);
不工作。我会很感激任何建议。
【问题讨论】:
-
对于任何指针(或数组)
p和索引i,表达式p[i]完全等于*(p + i)。指针算法只是索引“数组”的一种奇特方式。 -
... 或者更确切地说,
p[i]只是*(p + i)的精美语法糖(原样)。 -
简单写
iterator = &ds[5];。 -
x++本质上是x=x+1,而不是x=x+sizeof(something)。 -
@Dukeling
x++确实与x = x + 1相同,但如果您检查指针的原始值,它确实具有将x推进sizeof *x字节的效果。
标签: c pointers operators pointer-arithmetic