Array values output incorrectly - c++

I am having a very simple function to input values. But I am getting a wired output. I get different values to what I am inserting? What am I doing wrong?
#include <iostream>
using namespace std;
void testFunc(float arr[], int sizeOfArray);
int main() {
int sizeOfArray = 4;
float arrA[] = {};
float arrB[] = {};
cout << "1st array VALUES" << endl;
testFunc(arrA, 4);
cout << "A -> ";
for(int i=0; i<sizeOfArray; i++){
cout << arrA[i] << " | ";
}
cout << endl;
cout << "2nd array VALUES" << endl;
testFunc(arrB, 4);
cout << endl << "B -> ";
for(int i=0; i<sizeOfArray; i++){
cout << arrB[i] << " | ";
}
cout << endl;
return 0;
}
void testFunc(float arr[], int sizeOfArray) {
for(int i=0; i<sizeOfArray; i++){
cout << "Insert val " << i+1 << ": ";
cin >> arr[i];
}
}

The float arrA[] = {} creates an array of floats with 0 size. When you iterate over it, you access an out of bound memory in here:
for(int i=0; i<sizeOfArray; i++);
You can list initialize an array and not specify the size of an array, using braces {...}. But in such case, the size is deduced from the elements in the list. You have empty list.
For example:
float arr[] = {}; // Empty
float arr[4]; // Four elements, all default initialized
float arr[] = {3.14, 1.61}; // Two elements, specified values
float arr[4] = {3.14, 1.61}; // Four elements, last two are value initialized
You will benefit from taking a look at these articles:
Why aren't variable-length arrays part of the C++ standard?
C++ Containers Library

Related

What should be the proper declaration of array while finding the largest number in array?

C++ This is my code in C++ for finding the largest number in array. When I was running in my IDE then there was no compilation error but it was not giving me output. I think the problem is in the declaration of array at line 8. I replaced the array declaration from line 8 to line 11 then it is working fine in my IDE. So I didn't get it that why the declaration of array was not working at line 8?
#include <bits/stdc++.h>
using namespace std;
int largest_in_array(int a[], int n);
int main() // main function
{
int n; // User will enter the size of array
int arr[n]; // Line 8
cout << "Enter the size of array: " << endl;
cin >> n;
// Line 11
cout << "\nEnter the elements of array: " << endl;
for (int i = 0; i < n; i++) // This loop will run for each element of array that user wants to enter
{
cout << "Enter the " << (i + 1) << " element:";
cin >> arr[i];
cout << endl;
}
cout << "Elements are: [";
for (int i = 0; i < n; i++) // Prints the elements of array
{
// cout << "Enter the " << (i + 1) << " element:";
cout << arr[i] << " ";
// cout << endl;
}
cout << "]";
int res = largest_in_array(arr, n); //Function call
cout << "\nLargest element in array is: " << arr[res] << endl;
return 0;
}
int largest_in_array(int a[], int n) // function that will return the index of largest element in array
{
int max = 0;
for (int i = 1; i < n; i++)
{
if (a[max] < a[i])
{
max = i;
}
}
return max;
}
You declare int arr[n]; before the user has entered a value into n. n has an indeterminate value when you read it and create arr.
You don't check that the user enters a positive value into n. Zero and negative sized arrays are not valid.
Other points:
bits/stdc++.h is not a standard header which makes your program not portable. Use the proper header files, like iostream etc.
arr[n] is a Variable Length Array (VLA) which is not part of standard C++. Make it a std::vector<int> arr(n); instead.
The use of std::endl is unnessesary. There is no need to flush the output streams here. Use \n instead.
Example:
#include <iostream>
#include <limits>
#include <vector>
int largest_in_array(const std::vector<int>& a) {
int max = 0;
for(int i = 1; i < a.size(); i++) {
if(a[max] < a[i]) {
max = i;
}
}
return max;
}
int main() // main function
{
int n; // User will enter the size of array
std::cout << "Enter the size of array:\n";
// check that input succeeds and that the value is valid
if(!(std::cin >> n) || n < 1) return 1;
std::vector<int> arr(n);
std::cout << "\nEnter the elements of array:\n";
for(int i = 0; i < n; i++)
{
std::cout << "Enter the " << (i + 1) << " element:";
if(!(std::cin >> arr[i])) {
std::cout << "invalid input, bye bye\n";
return 1;
}
}
std::cout << "Elements are: [";
for(int i = 0; i < n; i++)
{
std::cout << arr[i] << " ";
}
std::cout << "]";
int res = largest_in_array(arr); // Function call
std::cout << "\nLargest element in array is: " << arr[res] << '\n';
}
That said, you could however use the standard algorithm std::max_element instead of writing your own. It returns an iterator to the maximum element.
You could also make use of range-based for loop when you don't need to know the index in the array, as in your second loop.
Example:
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <iterator>
#include <limits>
#include <vector>
int main() {
int n; // User will enter the size of array
std::cout << "Enter the size of array:\n";
if(!(std::cin >> n) || n < 1) return 1;
std::vector<int> arr(n);
std::cout << "\nEnter the elements of array:\n";
for(int i = 0; i < n; i++) // This loop will run for each element of
// array that user wants to enter
{
std::cout << "Enter the " << (i + 1) << " element:";
if(!(std::cin >> arr[i])) {
std::cout << "invalid input, bye bye\n";
return 1;
}
}
std::cout << "Elements are: [";
for(auto value : arr) { // a range-based for loop
std::cout << value << ' ';
}
std::cout << "]\n";
auto res = std::max_element(arr.begin(), arr.end());
std::cout << "Largest element in array is: " << *res << '\n';
std::size_t index = std::distance(arr.begin(), res);
std::cout << "which has index " << index << '\n';
}
When you have int n on line 8 it is initialized when you use it to create the array. When n is initialized explicitly, it's value is undefined behavior. You may be creating an array larger than the n you inputted on line 10, resulting in the array having extra random junk, it may be smaller meaning your program read memory it really shouldn't, etc.

How do I change the size of an array and fill it with automated elements?

I have an array with set elements 1 - 10. I have decided the size of the array and I have decided the elements of the array. My question is, how do I create an array of size x and fill it with elements 1,2,3,4 . . .
//sets values of the array elements and print them.
cout << "Array should contain x integers set to 1,2,3" << endl;
// QUESTION: How can I change the size of the array and have
// have values automatically entered?
int array[] = { 1,2,3,4,5,6,7,8,9,10 };
for (int i = 0; i <= (sizeof(array) / sizeof(int)-1); ++i) {
// sizeof(array)/sizeof(int) = 36/4. ints are 4.
cout << "Element " << i << " = " << array[i] << endl;
}
cout << "The number of elements in the array is: "
<< sizeof(array) / sizeof(int) << endl;
cout << endl;
cout << endl;
you can use dynamic memory allocation approach for your array, there you can give as much size as you want. Thanks.
//Variable size of Array program to print Array elements
#include <iostream>
using namespace std;
int main()
{
cout << "Enter Array size x:" << endl;
int x = 0;
cin >> x;
int *ptrArray = new int[x];
//Inittialise Array
for (int i = 0; i < x; i++)
{
ptrArray[i] = i + 1;
}
//Print Array elemts
cout << "Array elements:";
for (int i = 0; i < x; i++)
{
cout << ptrArray[i] << endl;
}
delete[] ptrArray;
return 0;
}

Using pointer arithmetic to add the contents of two arrays and save to an empty array

So I have written a function that should simply add the values of each element stored in two separate arrays, and save them to a third array.
I don't understand what the issue is, I am simply adding together the value of the int stored at the location referenced by each of my pointers, and saving it to my third, empty, array.
My code compiles just fine, but when I loop to print the contents of my third array (which should contain the sum of the two previous arrays elements at their respective indexes) it just prints a bunch of memory addresses. What gives?
EDIT: I fixed my while loop to perform the arithmetic, and everything is working well. My working code is below. Hope it helps someone else.
#include<iostream>
#include<stdlib.h>
using namespace std;
void arrayAdd(int firstArray[], int secondArray[], int targetArray[], int size){
int *firstPtr = firstArray;
int *secondPtr = secondArray;
int *tragetPtr = targetArray;
while (firstPtr <= &firstArray[size - 1] ){
//add the first two array elements
*tragetPtr = (*firstPtr + *secondPtr);
// point to the next location
*firstPtr++;
*secondPtr++;
*tragetPtr++;
}
}
int main() {
int totalElements;
const size_t ARRAY_SIZE = 50;
int firstIntegerArray[ARRAY_SIZE];
int secondIntegerArray[ARRAY_SIZE];
int thirdIntegerArray[ARRAY_SIZE];
cout << "Please enter the total number of elements for your array: ";
cin >> totalElements;
for(int i = 0; i < totalElements; i++){
cout << "Please enter a value for the first array at index " << i << ": ";
cin >> firstIntegerArray[i];
}
for(int i = 0; i < totalElements; i++){
cout << "Please enter a value for the second array at index " << i << ": ";
cin >> secondIntegerArray[i];
}
//run our arrayAdd function
arrayAdd(firstIntegerArray, secondIntegerArray, thirdIntegerArray, totalElements);
cout << "The conents of your two arrays added together is; " << endl;
for(int i = 0; i < totalElements; i++){
cout << thirdIntegerArray[i] << ", ";
}
return 0;
}
A local array decays to a pointer when it is passed to a function, so you can't use sizeof on it anymore. Indeed this:
void arrayAdd(int firstArray[]) {
int *firstPtr = firstArray;
std::cout << "sizeof(firstArray) == " << sizeof(firstArray) << std::endl;
std::cout << "sizeof(firstPtr) == " << sizeof(firstPtr) << std::endl;
}
int main() {
int test[] = {1,2,3,4,5,6,7,8,9,0};
arrayAdd(test);
return 0;
}
Prints:
sizeof(firstArray) == 8
sizeof(firstPtr) == 8
on my 64 bit machine.
Casting int[] to int* doesn't change anything since it already became a pointer as an argument. You should pass the size of the array to the method or, since you are working with C++, use an std::array or std::vector which will just solve any problem.

why v[0] and *v.begin() printing 0 even though i am not passing some 0 as input value for array

#include <iostream>
#include <vector>
using namespace std;
int main()
{
int testcases = 0;
int length;
int item =0;
std::vector<int> v;
cin>>testcases;
for (int i=0; i<testcases; ++i)
{
cin>>length;
v.resize(length);
for (int j=0; j<length; ++j)
{
cin >> item;
cout << "item entered:" << item << endl;
v.push_back(item);
}
cout << v[0] << " ";
cout << *v.begin() << " ";
int loop=0;
cin>>loop;
int range1=0, range2=0;
int result = 0;
for (int k=0; k<loop; ++k)
{
result = 0;
cin>>range1;
cin>>range2;
cout << v[range1]<< " "<< v[range2] <<endl;
while (range1<=range2)
{
result = result^v[range1];
++range1;
}
cout << result << endl;
}
}
return 0;
}
why v[0] and *v.begin() printing 0 even though i am not passing some 0 as input value for array
It's because the push_back calls add to the end of the vector, which is after the items created by the resize call.
If you want to set specific entries in the vector, you need to use array indexing syntax in the input loop.

C++ Dynamic ND Arrays

I have a problem creating ND arrays dynamically.
So for example:
int **A = 0;
A = new int *[rowsA];
for (int i=0;i<rowsA;i++) {
A[i] = new int[columnsA];
for(int j=0;j<columnsA;j++) {
cout << "Enter " << "(" << i << "," << j << "): ";
cin >> A[i][j];
}
}
And passed to a function like: print_matrix(&A[0][0],rowsA,columnsA);
void print_matrix(int *A, int x, int y) {
for (int i=0;i<x;i++) {
for (int j=0;j<y;j++) {
cout << A[i+j*x] << " ";
}
cout << ",";
}
}
For example:
input : 1,2,3,4,5,6,7,8,9
output: 6-digitnumber 6-digitnumber 4,2 6-digitnumber 5,3 6-digitnumber 6
any ideas?
If by a ND array you mean an Iliffe vector, you aren't building it correctly. The data has to be allocated consecutively and thus in one allocation as the memory returned by successive calls to new isn't necessarily consecutive. This should do the work:
int **A = new int *[rowsA];
int *data = new int[rowsA*columnsA];
for (int i=0;i<rowsA;i++) {
A[i] = data + i*columnsA;
for(int j=0;j<columnsA;j++) {
cout << "Enter " << "(" << i << "," << j << "): ";
cin >> A[i][j];
}
}
Your A variable is an array of pointers (and each pointer points to a sequence of int's) - print_matrix expects a pointer directly to a sequence of int's. The two types are not compatible.
You'll need to either make print_matrix take an int **, or change the use of your A variable to be A[i+j*x] rather than A[i][j]