如果数组为空,sizeof()返回什么 [英] What does sizeof() return if array is empty

查看:295
本文介绍了如果数组为空,sizeof()返回什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个双[12] x ,其中没有元素。当提示用户时,他/她输入一个数字,该数字存储在 x 中。



我希望程序首先检查 x 是否为空,如果是,请将用户的输入放在 x [0]或者如果不是,请将用户的输入放在下一个免费索引中。



我这样做了:



I have a double[12] x which has no elements in it. When the user is prompted, he/she enters a number, which is stored in x.

I want the program to first check if x is empty and if it is, put the user's input in x[0] or if it isn't, put the user's input in the next free index.

I had done this:

...

double x[12];

    void AddPayment(double Amount)
    {
        int i = sizeof(x);

        x[i] = Amount;
    }





是否sizeof()不适用于数组,是否有更好的方法这样做?



Is it that sizeof() doesn't work with arrays, is there a better way of doing this?

推荐答案

double x [12]将为12个双打分配内存,无论这些是否真正得到了值...所以sizeof(x)是一个这里不变...

你有两个选择:

1.在每次输入后引入一个全局索引(x旁边)...

double x[12] will allocate memory for 12 doubles regardless if those actually got values or not...so sizeof(x) is a constant here...
You have two options:
1. introduce a global index (next to x) to incrase after every input...
double x[12]
int i = 0;

void AddPayment(double Amount)
{
    x[i] = Amount;

    i++;
}



(你必须照顾我> = 12)



2使用一些负值初始化数组并检查每一行中的第一个并更新...


(You have to take care of i >= 12)

2. Initialize the array with some negative value and check in each round where is the first and update...


简单数组在C或C ++中不能以这种方式工作。数组以指定的大小分配,并且没有填充或空的单元格的概念。他们都包含一些东西。所以 sizeof 运算符将始终返回数组的完整大小。



使用STL类,如 vector 代替。它们不仅允许您使数组变量大小,而且还可以跟踪已填充的单元格数。
Simple arrays don't work that way in C or C++. The array is allocated with the specified size and there is no concept of cells being filled or empty. They all contain something. So the sizeof operator will always return the full size of your array.

Use STL classes like vector instead. They not only allow you to make the array variable size, but also keep track of how many cells you have filled.


sizeof 返回对象的大小(以字节为单位)(参见此处: http://en.cppreference.com/w/cpp/language / sizeof [ ^ ])。



它不能用于您的目的。你需要一个额外的变量来存储下一个自由元素的索引:

sizeof returns the size of an object in bytes (see here: http://en.cppreference.com/w/cpp/language/sizeof[^]).

It can't be used for your purpose. You need an extra variable that stores the index of the next free element:
double x[12];
unsigned nextNdx = 0;

void AddPayment(double Amount)
{
    // Check if array not filled up
    if (nextNdx < sizeof(x) / sizeof(x[0]))
    {
        x[nextNdx++] = Amount;
    }
}



或者您可以使用 std :: vector [ ^ ]或 std :: array [ ^ ]。


这篇关于如果数组为空,sizeof()返回什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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