Click here to Skip to main content
15,886,830 members
Please Sign up or sign in to vote.
2.00/5 (2 votes)
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.

I had done this:

C++
...

double x[12];

    void AddPayment(double Amount)
    {
        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

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;

void AddPayment(double Amount)
{
    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...
 
Share this answer
 
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.
 
Share this answer
 
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;

void AddPayment(double Amount)
{
    // 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[^].
 
Share this answer
 
v2
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;


Please learn the basics ;-)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900