在C中访问数组的-1元素 [英] Accessing the -1 element of an array in c

查看:126
本文介绍了在C中访问数组的-1元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构体数组,它是动态分配的.指向该数组的指针将传递给其他函数.

I have an array of structs, which is dynamically allocated. A pointer to this array is passed around to other functions.

struct body{
    char* name; 
    double mass; 
    // ... some more stuff
    };

 body *bodies = malloc(Number_of_bodies*sizeof(body));

我需要知道数组的大小,所以我将大小存储在一个结构中,该结构位于数组的第0个元素(第一个结构)中.

I need to know the size of the array, so I'm storing the size in one of the structs, which is in the 0th element of the array (the first struct).

bodies[0].mass = (double)Number_of_bodies;

然后我从函数返回指向数组第1个元素的指针,即bodies[1]

I then return from the function a pointer to the 1st element of the array i.e bodies[1]

  return (bodies+1); 

现在,当我在其他函数中使用此指针时,数据应从第0个元素开始.

Now, when I use this pointer in other functions, the data should start at the 0th element.

  body *new_bodies = (bodies+1);     //Just trying to show what happens effectively when i pass to another function
  new_bodies[0] = *(bodies+1);       //I Think

如果我想查看位于bodies[0]的初始结构,这是否意味着在其他函数中我必须访问new_bodies[-1]?

If I want to see the initial struct, which was at bodies[0], does that mean in other functions I have to access new_bodies[-1] ?

这是我能做的吗? 如何访问初始结构?

Is this something I can do? How can I access the initial struct?

推荐答案

是的,您可以使用new_bodies[-1]访问数组的初始元素.这是完全合法的.

Yes, you can use new_bodies[-1] to access the initial element of the array. This is perfectly legal.

其背后的原因是指针算术:方括号是另一种编写+的方式,因此当您编写new_bodies[-1]时,它与*(new_bodies-1)相同.

The reason behind this is pointer arithmetic: square brackets is another way of writing +, so when you write new_bodies[-1] it is the same as *(new_bodies-1).

因为获得new_bodiesbodies+1,所以new_bodies-1(bodies+1)-1bodies,从而使new_bodies[-1]bodies[0]相同.

Since new_bodies has been obtained as bodies+1, new_bodies-1 is (bodies+1)-1, or bodies, making new_bodies[-1] identical to bodies[0].

注意:您似乎正在尝试将元素数增加到struct数组的初始元素中,从而为其重新定义了mass字段.从内存分配(指针name保持未使用)的角度来看,这将是可行的,但它不是次优的,而在可读性方面则是最重要的.您最好在struct中使用一个灵活的数组成员来显式地存储条目数:

Note: It looks like you are trying to shoehorn the number of elements into the initial element of the array of your structs, re-purposing the mass field for it. This will work, but it is suboptimal, both in terms of memory allocation (a pointer name remains unused) but most importantly in terms of readability. You would be a lot better off using a flexible array member in a struct that stores the number of entries explicitly:

struct body {
    char* name; 
    double mass; 
    // ... some more stuff
};
struct bodies {
    size_t count;
    body bodies[]; // <<== Flexible array member
};
...
bodies *bb = malloc(sizeof(bodies)+Number_of_bodies*sizeof(body));
bb->count = Number_of_bodies;

此处是另一个问答的链接,其中包含使用灵活数组成员的示例.

这篇关于在C中访问数组的-1元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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