如何在C中移动数组的起始索引? [英] How do you shift the starting index of an array in C?

查看:71
本文介绍了如何在C中移动数组的起始索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在C中切换一个int数组的起始索引.确切地说,我有以下数组:

I am trying to switch the starting index of an array of ints in C. To be precise I have the following array:

{ int array[4] = {1,2,3,4};}

我希望将{array}更改为包含{2,3,4}的3个项目的数组.我想知道是否有一种简单的方法可以使用指针而不移动数组中的所有元素.只要前三个项目为{2,3,4},如果{array}仍然是4个项目的数组,我也很高兴.我尝试了以下方法:

I wish to change {array} to an array of 3 items containing {2,3,4}. I was wondering if there was an easy way to do this using pointers and without shifting all the elements in the array. I am also happy if {array} remains an array of 4 items as long as the first 3 items are {2,3,4}. I tried the following:

{array = &(array[1])}

但是,这不起作用,并且我收到一条错误消息,提示{从类型'int *'分配为类型为'int [4]'的类型不兼容}.

However, this does not work and I get an error saying {incompatible types when assigning to type ‘int[4]’ from type ‘int *’}.

我的印象是C数组是对该数组第一个元素的引用.

I was under the impression that a C array was a reference to the first element of the array.

有人可以帮我吗?

推荐答案

您有一些选择:

移动一个元素剩下的所有元素

如果不需要保留内容:

int array[4] = { 1, 2, 3, 4 };

然后将元素从索引位置n复制/移动到索引位置n-1:

then you copy/move the elements from index position n to index position n-1:

例如:

int i;
for (i = 1; i < n; ++i)
  array[i-1] = array[i];

您也可以查看memmove,它可能更有效.

You can also look into memmove which might be more efficient.

例如,

memmove(array, array+1, sizeof array - sizeof *array);

与上面的循环具有相同的作用.

which does the same thing as the loop above.

将元素复制到新数组中,而忽略第一个

如果需要保留原始数据,则可以创建另一个数组,然后将元素复制到该数组中,而忽略第一个元素.

If preservation of the original data is required, then you can create another array and copy the elements into that ignoring the first element.

例如,

int array1[4] = { 1, 2, 3, 4 };
int array2[3];
int i;

for (i = 0, i < SIZE_OF_SMALLER_ARRAY; ++i)
  array2[i] = array1[i+1]

使用指针将array [1]称为array [0]

如果您想使用指针而无需移动/复制数据:

If you want to use pointer eliminating the need to move/copy data:

int array[4] = { 1, 2, 3, 4 };
int *pArray = &array[1];

现在pArray指向数组中的第二个元素,有效地使您可以将array [1]索引为pArray [0]

Now pArray points to the second element in the array effectively allowing you to index array[1] as pArray[0]

使用整数指针数组

int array[4] = { 1, 2, 3, 4 };
int *parray[3];

int i;
for (i = 0; i < SIZE_OF_SMALLER_ARRAY; ++i)
  parray[i] = &array[i+1];

注意事项

你不能做的一件事是...

One thing you can't do is...

int array1[4] = { 1, 2, 3, 4 };
array1 = &array1[1]; // !! Compiler Error !!

原因是array1non-modifiable l-value.本质上是一个常数.

The reason is array1 is a non-modifiable l-value. Essentially a constant.

您也不能这样做...

You also can not do this...

int array1[4] = { 1, 2, 3, 4 };
int array2[4] = array[1] // !! Compiler error !!

这里的原因是您无法在此上下文中初始化数组.

The reason here is you can not initialize an array in this context.

这篇关于如何在C中移动数组的起始索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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