Question about the efficiency of using an array or individual variables

In summary, the conversation discusses the efficiency of using array A[10] versus individual variables B(0..9) in a program. The individual variables may be faster due to their one-step access, while the array requires additional steps to access the desired value. The conversation also touches on the limitations of declaring arrays with a constant size and the use of vector as a workaround. Finally, the conversation explains the difference in initialization between {1} and {1, 1, 1, 1, 1, 1, 1, 1, 1, 1} for an array of boolean values.
  • #71
Jarvis323 said:
You can't make it work because it doesn't make any sense. If you want a new variable, then just use a different name. It won't be the same variable of course. It doesn't make a difference whether it's inside a function or not, you can't use the same name for two different variables. If it worked for you outside a function, then that's not what you did. Here are some examples.

C:
// this is wrong
vector< int > x;
vector< int > &  y = x;
vector< int > y( d ); // the name y is already used

// this is also wrong
vector< int > x;
vector< int > x; // the name x is already used

// this is also wrong
vector< int > x;
vector< int > x( d ); // the name x is already used

// this is also wrong
vector< int > x;
vector< int > x = d;// the name x is already used

// this is correct
vector< int > x = d;

// this is correct and exactly equivalent to the last version
vector< int > x (d);

// this is correct as well
vector< int > x;
x = d;

And it's not because it's a vector either.

C:
// this is wrong
int x;
int &  y = x;
int  y( d ); // the name y is already used

// this is also wrong
int x;
int x; // the name x is already used

// this is also wrong
int x;
int x( d ); // the name x is already used

// this is also wrong
int x;
int x = d;// the name x is already used

// this is correct
int x = d;

// this is correct
int x (d);

// this is correct as well
int x;
x = d;
I know what you are talking all along. I cannot make it work because the code vector<int>numSold(defaultNSold) cannot work in all situation, maybe that's answer to my question already, I cannot use this to copy vector in the function where I have to define the vector in the function parameters.
 
Technology news on Phys.org
  • #72
yungman said:
I know what you are talking all along. I cannot make it work because the code vector<int>numSold(defaultNSold) cannot work in all situation, maybe that's answer to my question already, I cannot use this to copy vector in the function where I have to define the vector in the function parameters.
No. It has nothing to do with functions or function parameters, or vectors, or copying. It's much much simpler and the same in every single case. You cannot declare two completely separate variables with the same name in the same scope. It's exactly the same reason you cannot do, int x; int x;, it's not that you cannot use int x; in some special case, it's that the name is already used. You can't do it in any case. Again, the copy constructor is not a copy function. It creates a another variable that is initialized based on the value of the other one.
 
  • #73
Here is an analogy that hopefully makes sense.

You go and buy a blender. You read the instructions. It says, to use the blender:

1) unpack the blender from the packaging
2) plug it in
3) press the on button

Later on, after you've already unpacked it and have used it once, you decide to move the blender into a new room. And then you want to turn it on. You read the instructions again, how to turn it on. But you find you cannot (1) unpackage the blender, because the packaging is gone. So your solution is you go to the store, buy a new blender, unpack that one, plug that one in, and press its on button. But the old blender is still not on. So you complain. How can I make my old blender work by buying a new blender, unpacking it and turning it on?

The answer is you can't, it's a different blender. The solution is to just plug the old blender in, and it doesn't make sense to unpack and already unpacked blender.
 
  • #74
Jarvis323 said:
Here is an analogy that hopefully makes sense.

You go and buy a blender. You read the instructions. It says, to use the blender:

1) unpack the blender from the packaging
2) plug it in
3) press the on button

Later on, after you've already unpacked it and have used it once, you decide to move the blender into a new room. And then you want to turn it on. You read the instructions again how to turn it on. But you find you cannot (1) unpackage the blender, because the packaging is gone. So your solution is you go to the store, buy a new blender, unpack that one, plug that one in, and press its on button. But the old blender is still not on. So you complain. How can I make my old blender work by buying a new blender, unpacking it and turning it on?

The answer is you can't, it's a different blender. The solution is to just plug the old blender in, and it doesn't make sense to unpack and already unpacked blender.
I know, it won't work. That's my conclusion already.
 
  • #75
I finally finish the program using the dumb way to copy vector. Works like a champ. I made it a lot fancier, instead of following the book use given set of number sold for each product, I can input the numbers as wish by user. then display the description, price, #sold and total dollar sold for each item and sort with the highest dollar amount first.
C++:
// This program display the title of the product, the unit cost and the total sales in 6 months
// And sort in the order of the highest dollar sales product first to the least.
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;

void getnumSold(vector<int>&); //To input the number of unit sold in 6 months, you can choose to input the number or use default.
void displayProd(vector<int>&, vector<float>);//displace the list of product and their cost.
void DollarSales(vector<int>&, vector<float>&);//Calculate the total dollar sold for each item.
void sortSales(vector <float>, vector<int>&);// Sort with highest dollar sold first.
void displaySales(vector<int>, vector<float>, vector<int>);// Display in order of the highest dollar sold first.const int Row = 9, ProdCol = 31;
char Prod[Row][ProdCol] = { {"(0)Six Steps to Leadership"}, {"(1)Six Steps to Leadership"}, {"(2)Road to Exellence"},
                {"(3)Seven Lessons of Quality"},{"(4)Seven Lessons of Quality"},{"(5)Seven Lessons of Quality"},
                {"(6)Teams Are Made, Not Born"}, {"(7)Leadership for the Future"}, {"(8)Leadership for the Future"} };

char Desc[Row][ProdCol] = { {"Book"}, {"Audio CD"}, {"DVD"},
                {"Book"}, {"Audio CD"}, {"DVD"},
                {"Book"}, {"Book"}, {"Audio CD"} };

float Price[] = { 12.95, 14.95, 18.95, 16.95,
                21.95, 31.95, 14.95, 14.95, 16.95 };

int pnAr[] = { 914, 915, 916, 915, 918,//   0, 1, 2, 3, 4
              919, 920, 921, 922 };//        5, 6, 7, 8

vector<int>DefaultNSold = { 842, 416, 127, 514, 437, 269, 97, 492, 212 };

int main()
{
    vector<int>itemNum = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };//Item number from 0 to 8
    vector<int>Sold(DefaultNSold.size());//recieve number sold for each item.
    vector<float>totalValue(DefaultNSold.size());
    getnumSold(Sold);//passing vector Sold to function getnumSold(). Return of #sold of each item
    DollarSales(Sold, totalValue); // pass #sold in vector Sold, and return total sold value of each item.
    displayProd(Sold, totalValue);//Show all the tittles of the items
    sortSales(totalValue, itemNum);// pass total sold value of each item to sort highest to lowest total $ of items.
                                    // also return the order of the items from highest to lowest for sorting.
    displaySales(Sold, totalValue, itemNum);// Display from highest to lowest the total sales of items.
    return 0;                    
}

void getnumSold(vector<int>& numSold)// get and return vector numSold to vector Sold
{
    char select;
    cout << " Enter y to use default numbers, any other character";
    cout << "for entering 6 new numbers: "; cin >> select;
    if ((select == 'y') || (select == 'Y'))
    {
        int row=1;
        cout << " In getnumSold, You chose to use default = {";
        for (row = 1; row < DefaultNSold.size(); row++)
        {
            numSold[row - 1] = DefaultNSold[row - 1];
            cout << numSold[row - 1] << " ";
        }
        numSold[row - 1] = DefaultNSold[row - 1];
        cout << numSold[row - 1] << "}\n\n";
    }
    else
    {
        cout << " You chose to enter 9 new sales number.\n\n";
        cout << "Enter number sold for the following\n\n";
        for (int row = 1; row <= DefaultNSold.size(); row++)
        {
            cout << "   " << left << setw(35) << Prod[Row-1] << left <<
                setw(15) << Desc[row-1] << "$" << Price[row-1] << " is:   ";
            cin >> numSold[row-1];
        }
    }
}
void displayProd(vector<int>& Sold, vector<float>totVal)// display the table of selections and price.
{
    cout << " In displayProd\n\n";
    cout << left << setw(35) << "     Product" << setw(15) << "Decription" << setw(10) << "Part num" <<
        setw(15) << "   Price" << setw(10) << "sold" << setw(17) << "total" << "\n\n";
    for (int line = 0; line < Row; line++)
    {
        cout << "  " << left << setw(35) << Prod[line] << left << setw(15) <<
            Desc[line] << setw(10) << pnAr[line] << "$" << Price[line] <<
            right << setw(10) << Sold[line] << setw(7) <<"$" << left <<  totVal[line] << "\n\n";
    }
}
void DollarSales(vector<int>&Sold, vector<float>&totalValue)// receive vector Sold and vector itemNum.
{                                                   // return to vector Sold.
    int size = Sold.size();
    for (int element = 0; element < size; element++)
    {
        totalValue[element] = Price[element] * Sold[element];
        //cout << totalValue[element] << "\n\n";
    }
}
void sortSales(vector <float>Ar, vector<int>& itemN)// receive vector Sold and vector itemNum.
//function return vector itemN that contain the order of the items sorted from lowest
// total sales to highest.
{
    int size = Ar.size();// find the size of the vector. 
    int startScan = 0, index, temp2;
    float temp1;
    do
    {
        index = startScan + 1; // startScan is the first element number, index is the following number.
        while (index < size)
        {
            if (Ar[startScan] < Ar[index])//comparing the lowest number element starting with AR[0] to the rest
            {                    // one by oneswitch with them if it is higher than the other elements.
                temp1 = Ar[startScan];    temp2 = itemN[startScan];
                Ar[startScan] = Ar[index];    itemN[startScan] = itemN[index];
                Ar[index] = temp1; itemN[index] = temp2;
            }
            index = index + 1;// to the next lower element to compare,  AR[1]->AR[2]-> AR[3]...
        }
        startScan = startScan + 1;
    } while (startScan < (size - 1));
}
void displaySales(vector<int>Sold, vector<float>totalValue, vector<int> itemN)
{
    cout << "\n\n\n\n After sorting with the highest dollar amount first \n\n";
    cout << left << setw(35) << "     Product" << setw(15) << "Decription" << setw(10) << "Part num" <<
    setw(15) << "   Price" << setw(10) << "sold" << setw(17) << "total" << "\n\n";
    int Row = Sold.size();
    for (int line = 0; line < Row; line++)
    {
        cout << "  " << left << setw(35) << Prod[itemN[line]] << left << setw(15) <<
            Desc[itemN[line]] << setw(10) << pnAr[itemN[line]] << "$" << Price[itemN[line]] <<
            right << setw(10) << Sold[itemN[line]] << setw(7) << "$" << left << totalValue[itemN[line]] << "\n\n";
    }
}

I am done with Chapter 8, this is a lot more difficult than any problem in the book on chapter 8. I use a lot of vectors instead of arrays so to make it easier to expand the number of items as needed. Only the old ones are in array that I did not convert to vectors.

I only put the text display arrays in global section, those are not going to be changed. All the vectors that the program work on are parameters passing to function from main. They stay local as much as possible. The program is calling function to do everything, the main is only about 12 lines.
 
Last edited:
  • #76
jedishrfu said:
The old programming mantra still holds:
_ I can make it fast
- I can make it cheap
- I can make it reliable

pick any two and let me know.

Of course, bosses today will pick two and then ding you on the one they didn't choose.

Never truer words spoken...
 
  • #77
For memory efficiency:

C++:
struct boolmap {
    char x:1;
    char y:1;
    char z:1;
};
 
  • #78
Dr Transport said:
Never truer words spoken...
I assume make it fast meaning the speed, not deliver the program fast. One thing I always told my people, do NOT rush, don't wait until the last minute to do the job. Take the time to do it right, think it out first, don't rush in.

I am proud to say in my career, hardware always ahead of schedule way before the mechanical and software group. I hate the marketing schedule, they think if they put in unrealistic schedule, they can pressure people to work faster. Nothing is more time wasting than doing it wrong, then having to bandage it back. That's wasting money, wasting time.

I monitor my people, make sure they take the time to do it right, quality control right from the beginning. Might have a slow start, but we always finish ahead.

Back to the 3 options: make it fast( as running speed), I pick 1 and 3 any time of the day. I talked about this many times here already how frustrating that the newer stuffs are getting slower and stupider. Too many fancy feature in the name of nobody left behind, that even the stupidest people can stumble through. I want things to respond fast. I want things that work. Nothing is more frustrating than my 2 year old car spent over 5 weeks in the shop the first 8 months ALL software problems. All the intermittents and lockups.

Nothing costs more money than a bad design and resort to bandage it up, then bandage the bandage.
 
  • #79
One thing that is way off the subject but is of utmost important for reliability...Programming FPGA. Software people might look at VHDL or AHDL( Altera's own language) and think it's easy as it looks like any computer language......Don't even think about it. The language is almost the same, but the effect is totally different. The difference is in software, everything is working is sequence, one step at a time. FPGA signal are working in PARALLEL. You might think you program one step at a time, but all steps are working at the same time in FPGA. If software people want to move into FPGA programming, make sure to take a basic digital class first, learn about timing and all before they even touch this. So many mistake are made because people don't understand. I wrote FPGA programming because I understand digital hardware. I program as if it is a circuit, not a program. I had to troubleshoot problems with FPGAs written by someone else. Any language is only a tool, it's only a means to an end. Have to know to big picture.

Funny in my gym, one guy was the top dog manager in Lockheed at the time, we were talking about about circuit design and topic landed on FPGA, when I was telling him all the trouble I had to go through troubleshooting the glitches from FPGAs, he offered me a job on the spot! I was laughing! I retired already, I have no intention of working again.
 
  • #80
I have a question on initialize pointer. The books said it's illegal to do this:
C++:
float myFloat;
int *pint = &myFloat;

I understand myFloat is a float, not an int. But the starting address of the variable myFloat is an int. Why can't you initialize int *pint to the address of myFloat?
 
  • #81
yungman said:
I have a question on initialize pointer. The books said it's illegal to do this:
C++:
float myFloat;
int *pint = &myFloat;

I understand myFloat is a float, not an int. But the starting address of the variable myFloat is an int. Why can't you initialize int *pint to the address of myFloat?
What do you think is the type of &myFloat?
 
  • #82
Jarvis323 said:
You need to slow down and learn what the code you are writing actually means, not just what you expect it to do.
+1
 
  • #83
yungman said:
C++:
float myFloat;
int *pint = &myFloat;
I understand myFloat is a float, But the starting address of the variable myFloat is an int. Why can't you initialize int *pint to the address of myFloat?
It's because there generally aren't just plain pointers -- they are almost always pointers to some particular type. In your example, myFloat is a pointer to type float. pint is a pointer to an int. You can't do what you're trying to do without some casts, and even then, you might not get what you expect.
Here's an updated version of your example.
C++:
float myFloat = 3.75F;
int * pInt = (int *)(&myFloat);
int val = *pInt;
Note that I'm using the old-style casts.
In this code, val gets set to 0x40700000, or decimal 1081081856. These are the integer representations of the float 3.75.
 
  • Like
Likes yungman
  • #84
Jarvis323 said:
What do you think is the type of &myFloat?
Integer!, it's the address of the first byte of the variable myFloat.

It points to the first byte of the variable, who cares whether it's a float or int or anything.
 
Last edited:
  • #85
yungman said:
Integer!, it's the address of the first byte of the variable myFloat.

It points to the first byte of the variable, who cares whether it's a float or int or anything.
There's your problem. You don't know what the type is.
 
  • #86
Jarvis323 said:
There's your problem. You don't know what the type is.
Is int *pint declare the ADDRESS?

Is &myfloat giving you the address of the first byte of the variable of myfloat?

It's the address, who cares about whether the content of myfloat is a float or int. It's the address.
 
  • #87
yungman said:
Is int *pint declare the ADDRESS?
No. It's a variable that can be used to store an address to an int. Its type is (int*).
yungman said:
Is &myfloat giving you the address of the first byte of the variable of myfloat?
It's giving you a value of a particular type (int*), that holds the first byte of the variable myfloat.

In C and C++ you have formal types with precise definitions, and the compiler does type checking to make sure the types you are using match up.

yungman said:
It's the address, who cares about whether the content of myfloat is a float or int. It's the address.
See Mark's post to see why it's not the same thing, and doesn't give the same results whether it's a float or int.
 
Last edited:
  • Like
Likes yungman
  • #88
Jarvis323 said:
In C and C++ you have formal types with precise definitions, and the compiler does type checking to make sure the types you are using match up.
I am ok if you said you are NOT allow to do this, I can obey that. BUT if the book said int *pint declares an address, and the address of a float is an integer, there is a problem. That's why I post the question here.

BTW, do NOT ever take what the books said is the truth. I challenged the most famous book on Phase Lock Loop and the author offered me to send me the manuscript of the latest version. They are only human.

I just read the Gaddis book and put it in the notes with page number. You can check if I am right, this is my understanding. It is on the notes of Chapter 9 page 496.
 

Attachments

  • Gaddis notes.docx
    63.3 KB · Views: 160
  • #89
yungman said:
I am ok if you said you are NOT allow to do this, I can observe that. BUT if the book said int *pint declares an address, and the address of a float is an integer, there is a problem.

There is no type that is called (address), or (integer) in the C++ type system. The book is not wrong. You just don't understand what a type is. What you are reading in the book is an english description of what it is, not what it's type is.
 
  • Like
Likes yungman
  • #90
Jarvis323 said:
There is no type that is called (address). And integer isn't a type in the C++ type system. The book is not wrong. You just don't understand what a type is.
Yes, it said int *pint define as address of pointer pint. int *pint initiates a pointer of address.
 
  • #91
yungman said:
Yes, it said int *pint define as address of pointer pint. int *pint initiates a pointer of address.
Right. It also has a type. The book described it, but didn't say what type it is. Where is the problem?
 
  • #92
Jarvis323 said:
Right. It also has a type. The book described it, but didn't say what type it is. Where is the problem?
You can have an address pointing to a float variable. All that means is pointing to the first byte of the float variable myFloat. The address is an integer.
 
  • #93
yungman said:
You can have an address pointing to a float variable. All that means is pointing to the first byte of the float variable myFloat. The address is an integer.
What is its type?
 
  • #94
Jarvis323 said:
What is its type?
myFloat is a float.

What is the address of the first byte of myFloat? Int or float?
 
  • #95
yungman said:
myFloat is a float.

What is the address of the first byte of myFloat? Int or float?
The type is (float*). Do you understand that?
 
  • #96
yungman said:
The address is an integer.

No, it isn't. The address is a pointer. "Pointer" and "integer" are different types in C. The fact that you, a human, can take the bits stored in a pointer and interpret them as an integer is irrelevant; C doesn't care and doesn't treat them the same way.

yungman said:
What is the address of the first byte of myFloat? Int or float?

Neither. It's a pointer. A pointer in C is a different type from either int or float.

More specifically, it's a pointer to a float, which is a different type in C from a pointer to an int.
 
  • Like
Likes Jarvis323
  • #97
PeterDonis said:
No, it isn't. The address is a pointer. "Pointer" and "integer" are different types in C. The fact that you, a human, can take the bits stored in a pointer and interpret them as an integer is irrelevant; C doesn't care and doesn't treat them the same way.
Neither. It's a pointer. A pointer in C is a different type from either int or float.

More specifically, it's a pointer to a float, which is a different type in C from a pointer to an int.
int *pint defines the address of the physical memory location. It HAS TO BE an integer. I designed plenty of real hardware with physical memory. It HAS to be integer. It cannot be a fraction. Take my word on this one. I can show you plenty of example of real schematic of address from A0 to whatever 64bits or 32 bits, it's INTEGER. This is physical hardware.
 
  • #98
yungman said:
int *pint defines the address of the physical memory location. It HAS TO BE an integer.

Sorry, but the actual workings of the C compiler trump your intuitions.

To the C compiler, an address is not an integer, it's a pointer, which is a different type from an integer. No amount of ranting by you will change that.

You can either accept this fact, or you can continue to waste the time of others here by asking questions to which you refuse to accept the correct answers.

yungman said:
I designed plenty of real hardware with physical memory.

We all understand how hardware works. But you don't understand how the C language and the C compiler work. And since you are trying to program in C, not enter hardware instructions directly into the hardware, it is knowledge about how C works that is relevant for this discussion. Knowledge that you do not have, and which you are never going to acquire if you refuse to listen to people who do have it.

yungman said:
It cannot be a fraction.

Nobody is saying it's a fraction. It's a pointer.

yungman said:
Take my word on this one.

No. The one who needs to be taking the word of others is you. Other people who know far more than you do about how the C language and the C compiler actually work are trying to help you. You need to listen to them, not demand that they listen to you.

If you are unable or unwilling to do this, your thread will end up getting closed. This one exchange has already taken up more time and energy from other posters than it should.
 
  • Like
Likes Mark44 and pbuk
  • #99
yungman said:
int *pint defines the address of the physical memory location. It HAS TO BE an integer. I designed plenty of real hardware with physical memory. It HAS to be integer. It cannot be a fraction. Take my word on this one.
As an example, a char is for storing an integer that is interpreted as an ascii2 character, its type is char.
 
  • #100
Jarvis323 said:
As an example, a char is for storing an integer that is interpreted as an ascii2 character, its type is char.

The OP's confusion is not about different ways bytes stored in memory can be interpreted. His confusion is about how the addresses of those bytes are interpreted.
 
  • Like
Likes yungman
  • #101
PeterDonis said:
The OP's confusion is not about different ways bytes stored in memory can be interpreted. His confusion is about how the addresses of those bytes are interpreted.
Yeah, but also confused about what types are. I was trying to get him to understand the distinction between integer and char, or integer and int*.
 
  • #102
PeterDonis said:
Sorry, but the actual workings of the C compiler trump your intuitions.

To the C compiler, an address is not an integer, it's a pointer, which is a different type from an integer. No amount of ranting by you will change that.

You can either accept this fact, or you can continue to waste the time of others here by asking questions to which you refuse to accept the correct answers.
We all understand how hardware works. But you don't understand how the C language and the C compiler work. And since you are trying to program in C, not enter hardware instructions directly into the hardware, it is knowledge about how C works that is relevant for this discussion. Knowledge that you do not have, and which you are never going to acquire if you refuse to listen to people who do have it.
Nobody is saying it's a fraction. It's a pointer.
No. The one who needs to be taking the word of others is you. Other people who know far more than you do about how the C language and the C compiler actually work are trying to help you. You need to listen to them, not demand that they listen to you.

If you are unable or unwilling to do this, your thread will end up getting closed. This one exchange has already taken up more time and energy from other posters than it should.
Read page 492 to 495 of Gaddis book
https://cplusplushelp.weebly.com/st...-control-structures-through-objects-book.htmlWhat is the physical address location of a float variable.
 
  • #103
Jarvis323 said:
Yeah, but also confused about what types are. I was trying to get him to understand the distinction between integer and char, or integer and int*.
I am trying to distinguish the address of the variable with the content of the variable.
 
  • #104
yungman said:
I am trying to distinguish the address of the variable with the content of the variable.
The & operator acts like a function, it takes myFloat as an argument and returns something. Both the argument myFloat and the returned value each have a C++ type. The type of the argument is (float). The return type is (float*). Those, with their exact syntax are valid types that the compiler can recognize and parse. The compiler flagged an error because (int*) is not the same type as (float*), and it has been decided by the C++ committee that this type mismatch should throw an error. Why? Because it can be problematic. As in Mark's post, getting the value from a pointer (de referencing) has to interpret the bits as something. Those bits could be encoding a float or an int, the only way to know is if the compiler keeps track of what is supposed to be there. If you really want to convert a value of type (float*), into a type (float*), then you can do type casting as Mark shows, where you ask the compiler to convert/consider the value of type (float *) as a type (int*), and maybe that means that the bits which were encoding 3.75 will now be encoding 1081081856 as far as the compiler knows.
 
Last edited:
  • Like
Likes yungman
  • #105
yungman said:
What is the physical address location of a float variable.

In C, it's represented by a pointer.

yungman said:
I am trying to distinguish the address of the variable with the content of the variable.

We all know that. We are trying to explain to you how C does that. It does that by having a separate type, pointer, which represents addresses of things.

More precisely, as has already been noted, for each type in C, C also has a corresponding pointer type; the C type "pointer to X" represents the address of something with type X.

So in your case, the address of a float variable would be represented in C by a variable of type "pointer to float". Which would be written as float *. So the correct way of coding the original snippet of yours that started this subthread, assuming your purpose was to store a pointer to a float variable, would be:

C:
float myFloat;
float *pFloat = &myFloat;
 
  • Like
Likes yungman

Similar threads

Replies
7
Views
2K
Replies
6
Views
2K
Replies
1
Views
1K
Replies
5
Views
2K
Replies
75
Views
5K
Replies
17
Views
2K
Replies
9
Views
2K
Back
Top