This question already has answers here:
Understanding pointers and local scope [duplicate]
(4 answers)
Closed 6 years ago.
I want to read from user input some numbers and then display them 5 on each line. My code is like this:
#include <iostream>
using namespace std;
const int INPUT_SIZE = 7;
void printValues(int *b) {
int counter = 0;
while (counter < INPUT_SIZE) {
cout << *(b+counter) << " ";
if ((counter + 1) % 5 == 0 && counter>0) {
cout << endl;
}
counter++;
}
cout << endl;
system("pause");
}
int * readValues() {
int b[INPUT_SIZE];
for (int i = 0; i < INPUT_SIZE; i++) {
cout << "Enter element on position: " << i << ": ";
cin >> b[i];
}
return b;
}
int main() {
int* b;
b = readValues();
printValues(b);
return 0;
}
However, when I try to print them, I get some weird numbers which I think are memory locations. How do I print an array and also how do I write a function that returns an array? I have little experience with pointers, as I only coded in Java so far.
Help much appreciated.
Your array, b, is a local variable inside the function readValues.
When readValues exits, the array is destroyed.
The pointer which you return from readValues is invalidated as soon as the function returns. Trying to use it (e.g. by passing it to printValues) is incorrect (formally, it causes undefined behaviour).
You may have caused some confusion by giving the same name b to a pointer variable in main as you do to the array b in readValues. They are entirely separate variables.
If you want to use the same array in your two functions, you need to make sure it lives in a scope which ensures it lives as long as you need it to. This could be by making it a local variable in main.
Related
This question already has answers here:
How to find the size of an array (from a pointer pointing to the first element array)?
(17 answers)
C sizeof a passed array [duplicate]
(7 answers)
Closed 4 years ago.
I'm facing some problems with my code in C++. I would like to know how can I discover the amount of elements in an array. Follow the code:
#include <iostream>
#include <cstdlib>
using namespace std;
int avg(int numbers[]){
int amount; // The problem is in. How can I discover the amount of elements in an array?
int sum = 0;
for(int i = 0; i < amount; i++){
sum += numbers[i];
}
return sum / amount;
}
int main(){
int q;
cout << "Type number of integers:" << endl;
cin >> q;
int numbers[q];
for(int i = 0; i < q; i++){
cout << "Type an integer value for number " << i+1 << ":" << endl;
cin >> numbers[i];
}
cout << "The average is " << avg(numbers) << endl;
return 0;
}
The standard array in C++ doesn't contain a way to access the size of the array, the best way to track this is to have an integer that is updated with the size of the array or to try using std::array and then use the .size() method.
In your example you are using a fixed size array anyway so you may want to store the q value as a member variable and that contains the array size. Notice that in your example the code will not work as q is not a constant integer. To declare an array without a constant integer you will need to use a pointer to the first element of the array ie: int* numbers = new int[q];.
This question already has answers here:
Return array in a function
(20 answers)
Closed 4 years ago.
I'm really confused on the theory behind this. Not sure how to return the array from my isAscending function so i can print out in the main.
#include <iostream>
#include <string>
using namespace std;
// Implement printArray here
void printArray(int array[], int n){
for (int i = 0; i < n; ++i )
cout << array[i] << endl;
};
// Implement isAscending here
int isAscending(int array[], int n){
for(int i = 0; i <= n; ++i){
for(int j = 0; j <= n; ++j){
if(array[i] > array[j+1]){
int temp = array[j+1];
array[j+1] = array[j];
array[j] = temp;
}
}
}
return printArray(array, n);
};
// DO NOT CHANGE MAIN FUNCTION BELOW
int main() {
int myarray[100];
cout << "Enter number of integers : ";
int n;
cin >> n;
cout << "Enter " << n << " integers" << endl;
for (int i = 0; i < n; i++)
cin >> myarray[i];
cout << "Contents of array : ";
printArray(myarray, n);
cout << "Output of isAscending: " << isAscending(myarray, n) << endl;
}
Should I use pointers to pass the elements in the array i am stuck.
The short answer is you don't. When you pass an array to a function, you're actually just passing a pointer to the first element (the array decays to a pointer when you pass it as an argument). This means that if you modify the array in the function, you're modifying the original array and not a copy. Therefore, your isAscending() function will bubble sort the array you called it on and it does not need to return anything.
Just a side note, it seems like the assignment simply wants you to check if an array is ascending, instead of sorting it. In that case, isAscending() should return a bool.
If you need a function to return an array, you can't just pass a pointer to the first element since the array goes out of scope as soon as the function returns. You could dynamically allocate the array, but that just creates a bunch of new problems. Another way might be to return the pointer to the first element of the array passed to it as an argument like this, but there isn't much point in doing that since the caller already has access to the array.
The best way would be to use something like std::array or std::vector, which you can return by value just like any other variable. I would also recommend getting a good book.
(I provided this answer besides flagging as a duplicate since I thought the answer of the duplicate question was not complete enough and might mislead someone into trying to return a pointer to a local array)
This question already has answers here:
getting size of array from pointer c++
(6 answers)
Closed 7 years ago.
Alright so this is probably a really simple question, I'm just really new to c++ and am struggling to understand most things. I've been asked to create an array that stores random numbers but the user is to define the size of the array. I then have to display all the numbers in the array. What I'm struggling with is displaying all elements of the array. At the moment, I'm pretty sure I've got the array part down, but I can only seem to display one number. Here's my code so far:
#include <iostream>
#include <cstdlib>
#include <stdlib.h>
#include <ctime>
using namespace std;
using std::srand;
using std::rand;
using std::time;
void Display(int *, int);
int main(void)
{
int userSize;
cout << "Please enter the size of the array: ";
cin >> userSize;
int* randArray = new int[userSize];
srand(time(NULL));
for (int i = 0; i < userSize; i++) {
randArray[i] = rand() % 20 + 1;
}
//Disregard the next few lines, I was just testing to see if anything was actually in the array.
/*cout << randArray[0] << endl;
cout << randArray[1] << endl;
cout << randArray[2] << endl;
cout << randArray[19] << endl;*/
Display(randArray, sizeof(randArray) / sizeof(int));
return 0;
delete[] randArray;
}
void Display(int *arrayData, int numElements)
{
for (int counter = 0; counter < numElements; counter++)
{
std::cout << *(arrayData + counter) << std::endl;
}
return;
}
I should also mention that the teacher provided us with the code after the line that deletes the array.
This is the question I have to answer: Ask the user for the number of elements to be stored in the array. You should then dynamically allocate the memory to hold this array, which will proceed to be used in the same way as the previous task (populating the array with random data, displaying the data to the
screen).
sizeof(randArray) does not tell you the number of bytes that you've allocated. Rather, it tells you the size of a pointer, which on your system happens to be the same as the size of an integer, so sizeof(randArray) / sizeof(int) returns 1 always. Instead use userSize as your second parameter in the function call to Display.
Also, you delete[] randArray after return 0. This is incorrect; nothing after the return 0 will be executed. You want it above instead.
Further, consider the use of std::vector instead (unless you are required to use a raw pointer for this assignment)
The problem is sizeof. It gives you the size of the type of the argument, not of what is behind. Your should pass userSize to Display().
You should also delete the array before you return. Code behind return never gets executed.
I am trying to use a function to sort through a char array full of words. The current issue I am having is that in my sortNames function I am getting the error, "expression must be a modifiable lvalue" at the part below
hold = nameArr[ii];
nameArr[ii] = nameArr[jj];
nameArr[jj] = hold;
I am guessing that its because I am trying to pass values through an array for some reason. I am struggling with understanding references and pointers and the such, and I imagine that is hurting me here as well. Any help with this would be fantastic, thank you in advance.
Here is my current code...
#include <iostream>
#include <string>
using namespace std;
char nameArr[20][15]; // array to store the 20 values
int val = 0; // variable to pass values to the array
int x = 0; // loop counter outside functions
//Function prototypes
void getNames(char (&nameArr)[20][15], int &val);
void sortNames( char(&nameArr)[20][15]);
//getNames Function
void getNames(char (&nameArr)[20][15], int &val)
{
int i = 0; // loop counter
cout << "Awesome, now lets input those names...\n" << endl;
for (i = 0; i < val; i++)
{
cout << "\nNAME " << i+1 << ": " << ' ';
cin >> nameArr[i];
}
cout << "\n\n\nThese are the names that you inserted:\n" << endl;
for (i = 0; i < val; i++)
{
cout << nameArr[i] << "\n" << endl;
}
}
// sortNames function
void sortNames( char(&nameArr)[20][15])
{
int n = 15; // max length of word
int ii = 0; // loop counter
int jj = 0; // other counter
string hold; // holding array
for (int ii = 0 ; ii < n ; ii++)
{
for (int jj = ii + 1; jj < n; jj++)
{
if (nameArr[ii] > nameArr[jj])
{
hold = nameArr[ii];
nameArr[ii] = nameArr[jj];
nameArr[jj] = hold;
}
}
}
}
int main()
{
cout << "NAME SORTER!\n\nPlease enter in the amount of names you wish to enter: " << ' ';
cin >> val;
getNames(nameArr, val);
cout << "\n\n\nAlright, lets sort now..." << endl;
sortNames(nameArr);
cout << "\nHere are the results:\n" << endl;
for (x = 0; x < val; x++)
{
cout << nameArr[x] << "\n" << endl;
}
system("pause");
}
Your main problem here is that you are trying to use an assignment operator on two fixed sized arrays, which isn't legal. Consider the following code:
int a[2] = {0, 0};
int b[2] = {1, 1};
a = b;
This gives the same error you are getting. On the lines you mentioned, you are doing the same thing with char[15] arrays.
To fix your problems, you either need to allocate your char array dynamically/work with the pointers, or a simpler solution would be to just change your char[][] array to a string[] array.
That being said, there are a lot of things you can clean up here:
You have a few variables declared globally that can just be defined in main or lower
You can declare loop counters inside the for loop instead of beforehand, as you do in the sortNames function
In sortNames you are declaring a few variables twice
I'll add a few things to dwcanilla's answer.
You will want to change your function prototypes and headers to something more like this:
void getNames(char ** & arr, int val);
void sortNames(char ** & arr);
What this means is that the function accepts a reference to an array of c-strings; that is, when you work with the array within the function you are modifying the actual array you passed and not just a copy. Also I think you'd be fine just passing the integer by value for getNames.
Second, global variables are generally a bad idea. Since you can pass the array reference directly to your functions you may want to declare nameArr and your other global variables inside main instead.
Third, in getNames you won't be able to use cin to assign your c-strings directly.
EDIT: This is a better way --
getting console input for Cstrings
Finally, the < operator doesn't work on c-strings the way you're using it in your sort function. Use strcmp() instead (and be sure to include the cstring header):
if(strcmp(arr[ii], arr[jj]) > 0)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am trying to find greatest number entered, and then display it to the user.
So once the user enters several numbers, program calls function that will find it and then return it. Unfortunately every time I run it, the number resets to zero even after the function has worked successfully. What do I do wrong?
Visual Studio mentions this: Run-Time Check Failure #3 - The variable 'gromax' is being used without being initialized.
int largestGroup(int groupsize[], int theValue)
{
int gromax=groupsize[0];
for (int i=1;i<9;i++){
if(groupsize[i] > gromax){
gromax=groupsize[i];
}
}
return gromax;
}
int main()
{
int groupsize[10]={0,0,0,0,0,0,0,0,0,0};
int gromax = groupsize[0];
char newentry='n';
do{
cin >> groupsize[i];
cout << string(60, '\n');
cout << "Would you like to enter another questionare? Enter either 'y' or 'n': " << endl;
cin >> newentry;
cin.ignore();
}while((newentry =='y') || (newentry=='Y'));
largestGroup(groupsize, i);
cout << "Number of customers in largest group today was " << gromax << endl;
Insert in the very beginning of main
int i = 0;
and inside the loop increase it as for example
cin >> groupsize[i++];
Change this
largestGroup(groupsize, i);
statement to
int gromax = largestGroup(groupsize, i);
And remove statement
int gromax = groupsize[0];
Also you shall check in the loop that you are not trying to acces a memory beyond the array.
And function largestGroup is wrong.
int largestGroup(int groupsize[], int theValue)
{
int gromax=groupsize[0];
This declares a function that - despite appearances - actually takes an array and an integer (inherited from C, arrays can decay to pointers as necessary, and it's deemed necessary when someone tries to pass them to functions).
Then, it declares a private local variable, gromax. This value, think of it as largestGroup::gromax, exists only for the life time of each individual call to the function. The last line of the function is then paramount.
return gromax;
}
This pushes the "gromax" into whatever CPU register/location return values are stored. It will live there until something else uses the value.
The language does not automatically transfer the value anywhere, even if your calling function has a variable of the same name.
So, the bug in your code is this:
largestGroup(groupsize, i);
You call the function, and you never capture the return value.
gromax = largestGroup(groupsize, i);
would capture the value.
Be aware that arrays are passed by address/pointer (live demo: http://ideone.com/DTkbFn)
#include <iostream>
void f(int groups[5], int x)
{
x = 3;
groups[x] = 999;
}
int main()
{
int groups[5] = { 0, 1, 2, 3, 4 };
int x = 10;
std::cout << "before: x = " << x << ", groups[3] = " << groups[x] << '\n';
f(groups, x);
std::cout << "after: x = " << x << ", groups[3] = " << groups[x] << '\n';
return 0;
}
When you pass an array, you are actually passing by pointer, so normal "pass by value" behavior does not apply.
int largestGroup(int groupsize[], int thevalue)
is actually equivalent to
int largestGroup(int* groupsize, int theValue)
It is advisable to use the second syntax to avoid falling into the trap of thinking you can modify groupsize with no impact on the caller.
You didn't use the return value. Try:
gromax = largestGroup(groupsize, 1);