Using String Size to Declare Array Size? - c++

Sorry beginner here. I'm trying to get the string size from the cin function, then use that to declare array size. But it's saying:
line 17: request for member 'size' in 'x', which is non-class type 'std::string long int'.
It works fine without the array though.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int y;
string x[y];
cout << "Enter sequence" << endl;
cin >> x[y];
y = x.size;
for (int i = 0; i > y; i++)
cout x[i];
cout << "The size of the sequence is " << x.size() << " characters." << endl;
}

First, of all declaring an array as you do is not allowed. Let's take a look at these two lines of code
int y;
string x[y];
In the second line of code, what is the value of y? It could be anything. Certainly the compiler doesn't know, and the array size must be determined at compile-time.
There are two solutions to your problem:
Use pointers and dynamically allocate an array.
Use std::vector and let the standard library take care of the dynamic allocation.
IMO, both are tools which you should have in your programmer tool belt, so you should learn how to do both. You should also learn the advantages and disadvantages of either approach so that you can choose the correct one to solve a problem.
Finally, the error message that you get means that an array does not have a member called size(). If you fix this using solution 1. above, you will need to keep track of the size yourself.

Related

Why does this sortArray method in C++ (cpp) only sorts the first two numbers? [duplicate]

So my C++ instructor told us in class that there was no function to determine an array size in C++ and I was not satisfied with that. I found a question here on stackoverflow that gave this bit of code (sizeof(array)/sizeof(*array)) and while I don't exactly understand it, I understand it takes the total amount of memory allocated to the array and divides it by what I assume is the default memory allocation of its data type...(???)
I decided I wanted to practice writing functions (I'm in CS 111 - Fundamentals 1) and write a function that returned the number of elements in any array I passed it. This is what I wrote:
#include <iostream>
using namespace std;
int length_of_array(int some_list[])
{
// This only returns the integer 1 for some reason
return (sizeof(some_list)/sizeof(*some_list));
}
int main()
{
// Declare and initialize an array with 15 elements
int num_list[] = {2,4,6,8,10,12,14,16,18,20,22,24,26,28,30};
//Outputs what I assume is the total size in bytes of the array
cout << sizeof(num_list) << endl;
//Outputs what I assume to be size of memory set aside for each in element in an array
cout << sizeof(*num_list) << endl;
//This extrapolates array's number of elements
cout << "This is the output from direct coding in the\nint main function:\n" <<
(sizeof(num_list)/sizeof(*num_list)) << endl;
//This function should return the value 15 but does not
int length = length_of_array(num_list);
cout << "This is the length of the array determined\n";
cout << "by the length_of_array function:\n" << length << endl;
return 0;
}
The function returns 1 no matter what I do. Would somebody please give me a C++ specific workaround and explanation of how it works?
Thank you.
The problem is here:
int length_of_array(int some_list[]);
Basically, whenever you pass an array as the argument of a function, no matter if you pass it like int arr[] or int arr[42], the array decays to a pointer (with ONE EXCEPTION, see below), so the signature above is equivalent to
int length_of_array(int* some_list);
So of course when doing sizeof(some_list)/sizeof(*some_list) you will get the ratio between the size of the pointer the array decayed to and the size of the type representing the first element. In your case, 1, as it looks like on your machine the size of a pointer is probably 4 bytes (32 bits), same as the size of an int.
So my C++ instructor told us in class that there was no function to determine an array size in C++ and I was not satisfied with that.
YOUR TEACHER IS WRONG! There is a way of passing an array by reference and getting its size:
template<size_t N>
int length_of_array(int (&arr)[N])
{
std::cout << N << std::endl; // WORKS!
return N;
}

C++ median finder program works on 50% of random number sequences, can someone tell me why? [duplicate]

So my C++ instructor told us in class that there was no function to determine an array size in C++ and I was not satisfied with that. I found a question here on stackoverflow that gave this bit of code (sizeof(array)/sizeof(*array)) and while I don't exactly understand it, I understand it takes the total amount of memory allocated to the array and divides it by what I assume is the default memory allocation of its data type...(???)
I decided I wanted to practice writing functions (I'm in CS 111 - Fundamentals 1) and write a function that returned the number of elements in any array I passed it. This is what I wrote:
#include <iostream>
using namespace std;
int length_of_array(int some_list[])
{
// This only returns the integer 1 for some reason
return (sizeof(some_list)/sizeof(*some_list));
}
int main()
{
// Declare and initialize an array with 15 elements
int num_list[] = {2,4,6,8,10,12,14,16,18,20,22,24,26,28,30};
//Outputs what I assume is the total size in bytes of the array
cout << sizeof(num_list) << endl;
//Outputs what I assume to be size of memory set aside for each in element in an array
cout << sizeof(*num_list) << endl;
//This extrapolates array's number of elements
cout << "This is the output from direct coding in the\nint main function:\n" <<
(sizeof(num_list)/sizeof(*num_list)) << endl;
//This function should return the value 15 but does not
int length = length_of_array(num_list);
cout << "This is the length of the array determined\n";
cout << "by the length_of_array function:\n" << length << endl;
return 0;
}
The function returns 1 no matter what I do. Would somebody please give me a C++ specific workaround and explanation of how it works?
Thank you.
The problem is here:
int length_of_array(int some_list[]);
Basically, whenever you pass an array as the argument of a function, no matter if you pass it like int arr[] or int arr[42], the array decays to a pointer (with ONE EXCEPTION, see below), so the signature above is equivalent to
int length_of_array(int* some_list);
So of course when doing sizeof(some_list)/sizeof(*some_list) you will get the ratio between the size of the pointer the array decayed to and the size of the type representing the first element. In your case, 1, as it looks like on your machine the size of a pointer is probably 4 bytes (32 bits), same as the size of an int.
So my C++ instructor told us in class that there was no function to determine an array size in C++ and I was not satisfied with that.
YOUR TEACHER IS WRONG! There is a way of passing an array by reference and getting its size:
template<size_t N>
int length_of_array(int (&arr)[N])
{
std::cout << N << std::endl; // WORKS!
return N;
}

How to make the array size correct in C++?

I'm trying to create an array and the size of the array depends on the user input. But there is an error in my code, It said: "expression must have a constant value".
Here is my code:
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int var;
cout << "What size do you want to choose: "<< endl;
cin >> var;
int arr[var];
}
How can I change my code and make it work?
How can I change my code and make it work?
Change
int arr[var];
to
std::vector<int> arr(var);
This will require #include <vector>
The syntax you are using is known as a "variable length array", and is NON-STANDARD. Only a few compilers support it as an vendor-specific extension to the C++ language.
A standard compliant fixed-length array must have its size known to the compiler as a compile-time constant.
For what you want, you need to use the new[] operator instead:
int *arr = new int[var];
...
delete[] arr;
Or better, use a std::vector container:
#include <vector>
std::vector<int> arr(var);
To allocate an array dynamically, we use the array form of new and delete (often called new[] and delete[]):
#include <iostream>
int main()
{
std::cout << "Enter a positive integer: ";
int length{};
std::cin >> length;
int *array{ new int[length]{} }; // use array new. Note that length does not need to be constant!
std::cout << "I just allocated an array of integers of length " << length << '\n';
array[0] = 5; // set element 0 to value 5
delete[] array; // use array delete to deallocate array
// we don't need to set array to nullptr/0 here because it's going to go out of scope immediately after this anyway
return 0;
}
Arrays in C++ must have constant size known at compile-time. You can preallocate several constant sizes known at compile time and offer the user to choose one of them. Alternatively, you can use another data structure that allows dynamic size allocation e.g std::vector.
Good luck!

C++ Compiler passing by reference without me telling it to?

So I made a program earlier in the year that taught us how to use arrays. Just recently I was taught about the use of pointers and structures in C++. Now that I have that knowledge and understanding (or so I think), I am confused to how my earlier program managed to work!
Before I say more, here is the program code:
https://pastebin.com/AYyv2Bzt
special attention to my askSales function as it leaves me baffled
void askSales(int salesArray[], string namesArray[])
{
for (int counter = 0; counter <= NUM_OF_POS; counter++)
{
cout << "How many jars of " << namesArray[counter] << "sold? : ";
cin >> salesArray[counter];
while (salesArray[counter] < 0 )
{
cout << endl << "You cannot enter a negative number for sales. If no jars were\nsold please enter 0. Please answer prompt again."
<< endl << endl
<< "How many jars of " << namesArray[counter] << "sold? : ";
cin >> salesArray[counter];
}
}
}
Heres what I am confused about:
How in the world is my program able to modify the contents of the arrays passed to askSales when those arguments are not passed by reference?
In your function declaration and in the calls to it you get array-to-pointer decay.
This means your function is exactly equivalent to this:
void askSales(int* salesArray, string* namesArray)
And that obviously doesn't pass the array by value and create a new copy of the array, it passes a pointer to the original array. Which gives the effect of passing by reference (because the pointer refers to the original array outside the function).
Plain C++ arrays are never passed by value on their own. They decay into pointers.
In the declaration/definition of a function, the syntax T id[] (or even with a number, such as T id[4]) is just syntactic sugar for T *id. It's exactly the same thing.
When passing an array to a function, it is implicitly converted ("decays") to a pointer to its first element.
Note that the above only applies to plain arrays. In modern C++, you have the alternative of using std::array<T, n> to declare an array of n objects of type T. Since std::array is a class, it behaves like a class and does not have any such decay rules. Such an array is actually copied when passed by valaue.

When passing an array to a function in C++, why won't sizeof() work the same as in the main function?

So my C++ instructor told us in class that there was no function to determine an array size in C++ and I was not satisfied with that. I found a question here on stackoverflow that gave this bit of code (sizeof(array)/sizeof(*array)) and while I don't exactly understand it, I understand it takes the total amount of memory allocated to the array and divides it by what I assume is the default memory allocation of its data type...(???)
I decided I wanted to practice writing functions (I'm in CS 111 - Fundamentals 1) and write a function that returned the number of elements in any array I passed it. This is what I wrote:
#include <iostream>
using namespace std;
int length_of_array(int some_list[])
{
// This only returns the integer 1 for some reason
return (sizeof(some_list)/sizeof(*some_list));
}
int main()
{
// Declare and initialize an array with 15 elements
int num_list[] = {2,4,6,8,10,12,14,16,18,20,22,24,26,28,30};
//Outputs what I assume is the total size in bytes of the array
cout << sizeof(num_list) << endl;
//Outputs what I assume to be size of memory set aside for each in element in an array
cout << sizeof(*num_list) << endl;
//This extrapolates array's number of elements
cout << "This is the output from direct coding in the\nint main function:\n" <<
(sizeof(num_list)/sizeof(*num_list)) << endl;
//This function should return the value 15 but does not
int length = length_of_array(num_list);
cout << "This is the length of the array determined\n";
cout << "by the length_of_array function:\n" << length << endl;
return 0;
}
The function returns 1 no matter what I do. Would somebody please give me a C++ specific workaround and explanation of how it works?
Thank you.
The problem is here:
int length_of_array(int some_list[]);
Basically, whenever you pass an array as the argument of a function, no matter if you pass it like int arr[] or int arr[42], the array decays to a pointer (with ONE EXCEPTION, see below), so the signature above is equivalent to
int length_of_array(int* some_list);
So of course when doing sizeof(some_list)/sizeof(*some_list) you will get the ratio between the size of the pointer the array decayed to and the size of the type representing the first element. In your case, 1, as it looks like on your machine the size of a pointer is probably 4 bytes (32 bits), same as the size of an int.
So my C++ instructor told us in class that there was no function to determine an array size in C++ and I was not satisfied with that.
YOUR TEACHER IS WRONG! There is a way of passing an array by reference and getting its size:
template<size_t N>
int length_of_array(int (&arr)[N])
{
std::cout << N << std::endl; // WORKS!
return N;
}