15,877,915 members
See more:
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.

C++
```...

double x[12];

{
int i = sizeof(x);

x[i] = Amount;
}
```

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

## Solution 2

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...
C++
```double x[12]
int i = 0;

{
x[i] = Amount;

i++;
}```

(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...

## Solution 3

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.

## Solution 4

`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:
C++
```double x[12];
unsigned nextNdx = 0;

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

Alternatively you can use std::vector[^] or std::array[^].

v2

## Solution 1

The result of sizeof operator is the byte size of the input.

For getting the element size:
C++
`int elSize = sizeof(x)/sizeof(x[0]);`

if you want to access an element of you array you must access it this way:
C++
```int i = 0;//index of element, must be 0...11 (smaller than 12)
x[i] = Amount;```