reverse c++ array - c++

my aim is to reverse an array 3,12,2,1 to 1,2,12,3. when i run this code i get garbage before my actually result. i can't seem to see where the problem is please assit
#include<iostream>
using namespace std;
int rev (int arr[], int a){
//int r;
for(int i =a-1; i>=0; i--){
cout<<arr[i]<<" ";
}
return 0;
}
int main(){
int arr[] = {6,41,12,5,2};
cout<<"The rev of {6,41,12,5,2}"<<endl;
cout<<rev(arr, sizeof(arr))<<endl;
system("pause");
return 0;
}

Use sizeof(arr)/sizeof(arr[0]) instead of sizeof(arr).
sizeof(arr) gives the total size of the array. sizeof(arr[0]) is the size of one array element (all elements have the same size). So sizeof(arr)/sizeof(arr[0]) is the number of elements.

An optimized answer to the question would be using reverse () from STL if you are allowed to use it:
std::reverse
http://www.sgi.com/tech/stl/reverse.html
int main()
{
int arr[] = {6,41,12,5,2};
cout<<"The rev of {6,41,12,5,2}"<<endl;
reverse(arr, arr + 5);
copy(arr, arr + 5, ostream_iterator<int>(cout, ", "));
}

sizeof return the size in bytes. In your example, if sizeof(int) = 4, it returns 20.

Because you're using an array, you have to keep the size of the array handy as well. sizeof computes the size of a value in memory, in this case the size of all the memory used to represent arr. You can do sizeof(arr)/sizeof(int) to get the number of elements in an array. This makes sense because it's taking the total size of the array and dividing it by the size of an element in the array. Beware however that this only works for arrays (int arr[4] = {6,41,12,5,2};). If it's a pointer to a heap-allocated array via something like int* i = new int[4]; you'll need to keep the size of the array hanging around.
Also, you're calling your reverse function from within a cout<< call, which will print the function's return value (in this case it's hard-coded to 0).
It also turns out there is a function in the C++ standard library (std::reverse) that can do this.

If I may speak subjectively and in an off-topic manner about your approach, it is very un-C-like. My personal favorite way to reverse an array goes like this:
void reverse(int *a, int n)
{
int *p = a, *q = a + n - 1;
while (p < q)
{
int swap = *p;
*p++ = *q;
*q-- = swap;
}
}
// Usage:
int a [] = { /* ... */ };
reverse(a, sizeof(a)/sizeof(*a));
Of course, since your question is tagged c++, there's always std::reverse().

Sizeof operator return the one extra (arrayLength + 1) here 6 will return when passs 6 it store in a when a-1 you get 5 but array index start from 0 length-1 that from 0 to 4 here i pointing to index 5 that is not last element last+1 that why you got garbage value

Related

Printing out an entire array multiple times

I am wondering how you can print out an entire array multiple times in C++. Say you have the following array:
arr1 = [1,2,5,6,7,8]
and you want to print it out n times such that the output would be:
1 2 5 6 7 8
1 2 5 6 7 8
1 2 5 6 7 8
If n would be equal to 3. You could just code some number of for loops if n is a static integer, but what if it's dynamic?
I know you need to use a for loop for printing out all the contents of an array, but I'm not sure what you would do if you want to get the above output.
If n is dynamic, it doesn't matter. You can have a loop that prints the array n times quite easily:
void printInts(int* arr, size_t size) {
// some printing logic
}
int main() {
int arr[] = {0,1,2,3,4,5,6,7,8};
int n = 3; // could be anything really
for(int i = 0; i<n; i++) {
printInts(arr, 9);
}
}
The value of n doesn't really matter here: it should print n times.
If you're asking how do we know the size of arr if it's a dynamic array, that's actually pretty easy too:
Until C++11:
size_t size = sizeof(arr)/sizeof(arr[0]);
After C++11 you can use:
size_t size = *(&arr + 1) - arr;
You could do this in main() or even in printInts() if you want.
Note: keep in mind you can't get the size of a pointer allocated dynamically easily. If you allocate with say new, you'll have to keep track of the size of the array yourself.
You can't. The size of an array allocated with new[] is not stored in any way in which it can be accessed. Note that the return type of new [] is not an array - it is a pointer (pointing to the array's first element). So if you need to know a dynamic array's length, you have to store it separately.
If what you're asking is how to get user input:
int n;
cin >> n;
for (int i = 0; i < n; i++) {
// print array
}
I think you know how to use for loop.
int rows;
int arr1 [5] = {1, 2, 3, 4, 5};
cout << "Enter number of rows? ";
cin >> rows;
for(int row=1; row<=rows;row++) {
for(int index=0;index<=4;index++) {
// print the array index here and space after a digit
}
// print line-break here
}

how do i create dynamic array in cpp

I have this function:
void reverse(int* nums, unsigned int size)
This function is supposed to reverse the values in the array it is getting.
Now for reversing I thought to create another array with the size of the array passed in. Assigning this new one from the end of the original array to the start.
But I am a kind of new in C++, So I don't know how to create dynamic array in the size of the parameter of the function.
It's actually not necessary to allocate a new array here. See if you can find a way to solve this problem just by rearranging the existing elements in-place.
Given that this seems like it's an exercise with pointers, you can allocate space by using the new[] operator:
int* auxiliaryArray = new int[size];
You'd then free it by writing
delete[] auxiliaryArray;
However, this isn't the preferred way of doing this in C++. The better route is to use std::vector, which does all its own memory management. That would look like this:
std::vector<int> auxSpace(size);
You can then access elements using the square brackets as you could in a real array. To do this, you'll need to #include <vector> at the top of your program.
In C++, the recommended way to create an array of variable size would be to use an std::vector
#include <vector>
void reverse(int* nums, unsigned int size)
{
std::vector<int> V(size);
...
}
But that approach isn't the best here for performance because it requires additional memory to be allocated of the size of the array, which could be big. It would be better to start from the outside of the array and swap members one by one that are at mirroring positions (so if the size is 5, swap 0 and 4, then swap 1 and 3 and leave 2 alone). This only requires temporary storage of a single int.
You can do it without the need to create another array:
void reverse(int* array, const int size){
for(int i = 0; i < size / 2; i++){
int tmp = array[i];
array[i] = array[size - 1 - i];
array[size - 1 - i] = tmp;
}
}
int main(){
int array[] = {1, 3, 5, 7, 9, 11};
const int size = sizeof(array) / sizeof(array[0]);
reverse(array, size);
for(int i(0); i < size; i++)
std::cout << array[i] << ", ";
}
As you can see above in the loop you only need to swap the first element (element 0) with the n-1 element and the second one with n-1-1 and son on...
Remember arrays are indexed from 0 through n-1.
If you want to allocate new array which is not practical:
int* reverse2(int* array, const int size){
int* tmp = new int[size];
for(int i(size - 1), j(0); j < size; j++, i--)
tmp[j] = array[i];
return tmp;
}
int main(){
int array[] = {1, 3, 5, 7, 9, 11};
for(int i(0); i < size; i++)
std::cout << array[i] << ", ";
std::cout << std::endl;
int* newArray = reverse2(array, size);
for(int i(0) ; i < size; i++)
std::cout << newArray[i] << ", ";
std::cout << std::endl;
delete[] newArray;
return 0;
}
If you want to use a new array you can, but I think is to kill flies with a cannon.
Looks like you are using plain C code and not C++. I say that because of the signature of the function. The signature of the function in a common C++ code could be something like this other:
void reverse(std::vector& items);
You can reverse the current array without a new array, using the current one. You are passing the pointer to the first item of the array, and the content is not constant so that you can modify it. A better signature for the function could be:
void reverse(int* const nums, const unsigned int size);
Looks like a pointer problem. Think about the boundaries to iterate the positions of the array. Would you need to iterate the whole array? Maybe only half array? ;)
As bonus track, what about to exchange the values without an auxiliar variable? (this is true into this case that we are using the fundamental type int... remember the binary arithmetic).
array[pos_head] ^= array[pos_tail];
array[pos_tail] ^= array[pos_head];
array[pos_head] ^= array[pos_tail];

Arrays passed to function in C++ giving different lengths

I want to say first - I'm as interested in what's happening "behind the scenes" to cause this problem as I am in a blind fix for the code. Perhaps the C++ standard or something I'm unfamiliar with dictates what's causing it :-)
Anyways...
I am trying to pass 3 arrays, A, B, C into a function, which will merge A and B, storing the result in C.
Function declaration: void merge(int* a, int* b, int* c)
Passed from main() by:
int A[] = {1,2,3,4};
int B[] = {6,7,8,9};
int* C; //this could be wrong, btw!
merge(A, B, C);
Issue 1.
What's strange is that in main(), if I print the result of sizeof(A)/sizeof(A[0]), it gives me the proper result for the "length" of the array - 4 - and the same thing for B. But when I pass the arrays to the function, I try to calculate the size again, by the same method, but I get the result 2 for both arrays. The first lines of merge():
void merge(int* a, int* b, int* c)
{
int sizeA = sizeof(a)/sizeof(a[0]);
int sizeB = sizeof(b)/sizeof(b[0]);
int totalsize = sizeA + sizeB;
std::cout << "size A = " << sizeA << std::endl; //prints 2
std::cout << "size B = " << sizeB << std::endl; //prints 2
std::cout << "total = " << totalsize << std::endl;
...
Issue 2.
Just for fun, I tried iterating through a and b passed to merge() (within the merge function):
for (int i = 0; i < 4; ++i)
std::cout << a[i]; //prints "1234" as expected
All cool. But when I increase the index limit to 8...
for (int i = 0; i < 8; ++i)
std::cout << a[i]; //prints "12346789" - A and B concatenated!
Raising the max index a couple more times because why not:
for (int i = 0; i < 10; ++i)
std::cout << a[i]; //prints "1234678900"
...
for (int i = 0; i < 11; ++i)
std::cout << a[i]; //prints "1234678900-444896443"
Undefined behavior from out of bounds indexing and accessing other memory, I guess.
Printing b in the same manner does similar:
looping to i = 4 prints the array - 6789
to 6 adds two zeroes - 678900
to 8 adds the other stuff - 678900-126926969126613
Printing C, of course, results in nothing.
Are these oddities the result of
the fact I'm using C++ Shell (with options -std=c++14 -Wpedantic -O2) ?
incorrect passing of arrays to merge() ?
incorrect initializations in main() ?
the arrays needing to have a terminator, like char arrays?
all of the above?
In the first case, you have an array, which is not the same as a pointer. So the sizeof is correctly computed. Whereas int* is a pointer, and an array passed to a function always decays to a pointer (except when passing by reference). Also sizeof(int*)/sizeof(int) is the size of the pointer on your machine divided by the size of the int, so if your system is a 64 bit (8 bytes) and the int has a typical size of 4, you get 8/4=2.
Typical undefined behaviour by indexing out of bounds.
Advice: use std::vector<int> instead and you'll avoid allocating memory for C and using sizeof. You can simply use the std::vector::size() member function to obtain the size of the vector.
When you are passing your array to void merge(int* a, int* b, int* c)
The a and b here are no longer arrays, but are pointers. So when you are calculating it's size using
int sizeA = sizeof(a)/sizeof(a[0]);here sizeof(a)will give you the size of pointer, and sizeof(a[0]is giving you the size of int. Hence the result.
And for your second issue, when you are increasing the indexes, and getting both arrays connected, it is just because both arrays have been allocated continuous memory block, it is not necessary though that they will always be assigned continuous memory blocks, and other outputs are because of Undefined behavior only.
you need to remember that sizeof is a keyword that expands in compile time to the relevant size. sizeof(T) will expand to the byte size of (T).
inside the main function, sizeof(a) will give you the number of bytes of int[4], inside different function, the array decays into a pointer. sizeof(T*) is not sizeof(T[4])! you are calculating the size of the pointer (after the decay) and not the size of the real array. now let say my object weight 1 MB, does sizeof(OBJ) == sizeof(OBJ*)? of course not.
you are having Undefined beaviour. in this specific example, A and B sit right after the another on the stack. so in this super specific case when iterating over the stack you actually print both of the arrays because they sit one after the another. but again , this is Undefined beaviour. different compilers can padd the area between the array, or other OS may even kill your program.
You cannot compute a size of an array with a simple pointer passed to a function.
sizeof(integers) / sizeof(integers[0])
will be simply replaced by
sizeof(pointer on integer) / sizeof(integer).
But you can compute it earlier and then pass the size to a function like below.
#include <iostream>
using namespace std;
void doSomeWork(int* integers, const size_t size)
{
for (size_t i = 0; i < size; ++i)
{
std::cout << integers[i] << std::endl;
}
}
int main()
{
int integers[] { 0, 1, 2, 3 };
const size_t size = sizeof(integers) / sizeof(integers[0]);
doSomeWork(integers, size);
return 0;
}
As said below, std::vector<int> is much better than playing with C arrays.
There are already plenty of good answers here. In short, C++ arrays are of fixed size. If you want to change it, you have to use pointers and dynamic allocation. That can be tedious. the reason for most people here to advise you to use vectors instead.
Vectors are build for being of dynamic and adjustable size. You can use them almost like arrays. Here your code adapted:
void merge(vector<int> &a, vector<int>& b, vector<int> &c) // pass by reference
{
int sizeA = a.size();
int sizeB = b.size();
int totalsize = sizeA + sizeB;
c.resize(totalsize); // easy !
// ...
}
int main() {
vector<int> A{1,2,3,4};
vector<int> B {6,7,8,9};
vector<int> C;
cout <<A[2]<<endl; // access elements exacly like arrays
merge(A, B, C);
}

How can we find out in which element in an array the address and value came from in c++

For example: int a[4] = {2, 4, 34}
Lets say the address of a[0] is at 2000 and we know the value of the element at a[0] is 2.
Given only a memory address and a value of an element, is it possible to determine the position of the element in the array?
If so, please provide an example on how to do this.
Is this what you are looking for? Just using some pointer arithmetic;
int main ()
{
int ary[] = { 1, 2, 3, 5 };
int * address_of_2 = &ary[ 1 ];
int index_of_2 = address_of_2 - ary;
return 0;
}
The memory location will be unique for each element in the array. So yes, if you know the memory location, you can iterate through the array and simply find when the reference equals your value.
for (int i=0; i < arr_size; i++) {
if (&arr[i] == address && arr[i] == *address) {
cout << i << endl;
break;
}
}
If given an array, the size of the array and type of element(i.e. integer), than yes, given also the address of an element and the value, you could sort through the array and find its position. Note the significance that the array block is contiguous.
array = array;
n = sizeof(array)/sizeof(*array);
oAddress = array;
fAddress = array + n * sizeof(*array);
locOfElement = (elementAddress - oAddress) / (fAddress - oAddress) * n;

Int Array Length C++

I have to use a dynamic length int array in my program, and want to be able to get the number of objects in it at various points in my code. I am not that familiar with C++, but here is what I have. Why is it not giving me the right length? Thanks.
<#include <iostream>
Using Namespace std;
int length(int*);
void main()
{
int temp[0];
temp[0] = 7;
temp [1] = 10;
temp[2] = '\0';
cout << length(temp) << endl;
}
int length(int* temp)
{
int i = 0;
int count = 0;
while (*temp + i != '\0')
{
count++;
i++;
}
return count;
}
currently it just goes into an endless loop ;_;
In C++ arrays are not dynamic. Your temp array has zero length, and attempting to write to members beyond its length is undefined behaviour. It's most likely not working as it will be writing over some part of the stack.
Either create a fixed size array with enough space to put everything you want to in it, or use a std::vector<int> which is a dynamic data structure.
#include <iostream>
#include <vector>
using namespace std;
int length(int*);
int main () // error: ‘::main’ must return ‘int’
{
int temp[3];
temp[0] = 7;
temp[1] = 10;
// don't use char constants for int values without reason
temp[2] = 0;
cout << length(temp) << endl;
vector<int> vec_temp;
vec_temp.push_back(7);
vec_temp.push_back(10);
cout << vec_temp.size() << endl;
}
int length(int* temp)
{
int i = 0;
int count = 0;
while (*(temp + i) != 0) // *temp + i == (*temp) + i
{
count++;
i++; // don't really need both i and count
}
return count;
}
For the vector, there's no need to specify the size at the start, and you can put a zero in, and finding the length is a simple operation rather than requiring a loop.
Another bug inside your loop was that you were looking at the first member of the array and adding i to that value, rather than incrementing the pointer by i. You don't really need both i and count, so could write that a couple of other ways, either incrementing temp directly:
int length(int* temp)
{
int count = 0;
while (*temp != 0)
{
++count;
++temp;
}
return count;
}
or using count to index temp:
int length(int* temp)
{
int count = 0;
while (temp[count] != 0)
++count;
return count;
}
This approach is a bad idea for a couple of reasons, but first here's some problems:
int temp[0];
This is an array of 0 items, which I don't even think is permitted for stack elements. When declaring an array like this you must specify the maximum number of values you will ever use: E.g. int temp[10];
This is super important! - if you do specify a number less (e.g. [10] and you use [11]) then you will cause a memory overwrite which at best crashes and at worst causes strange bugs that are a nightmare to track down.
The next problem is this line:
while (*temp + i != '\0')
That this line does is take the value stores in the address specified by 'temp' and add i. What you want is to get the value at nth element of the address specified by temp, like so:
while (*(temp + i) != '\0')
So that's what's wrong, but you should take five minutes to think about a better way to do this.
The reasons I mentioned it's a bad idea are:
You need to iterate over the entire array anytime you require its length
You can never store the terminating element (in this case 0) in the array
Instead I would suggest you maintain a separate value that stores the number of elements in the array. A very common way of doing this is to create a class that wraps this concept (a block of elements and the current size).
The C++ standard library comes with a template class named "vector" which can be used for this purpose. It's not quite the same as an array (you must add items first before indexing) but it's very similar. It also provides support for copying/resizing which is handy too.
Here's your program written to use std::vector. Instead of the 'length' function I've added something to print out the values:
#include <vector>
#include <iostream>
void print(std::vector<int> const& vec)
{
using namespace std;
for (size_t i = 0; i < vec.size(); i++)
{
cout << vec[i] << " ";
}
cout << endl;
}
int main()
{
std::vector<int> temp;
temp.push_back(7);
temp.push_back(10);
print(temp);
return 0;
}
You could try:
while (*(temp + i) != '\0')
Your current solution is calculating temp[0] + i (equals 7+i), which apparently is not what you want.
Not only C++ arrays are not dynamic as Pete points out, but only strings (char *) terminate with '\0'. (This is not to say that you can't use a similar convention for other types, but it's rather unusual, and for good reasons: in particular, relying on a terminator symbol requires you to loop through an array to find its size!)
In cases like yours it's better to use the standard library.
#include <vector>
#include <iostream>
int main()
{
std::vector<int> v;
v.push_back(7);
v.push_back(10);
std::cout << v.size() << std::endl;
return 0;
}
If you don't want to use std::vector, try this:
#include <iostream>
using namespace std;
int main () {
int vet[] = {1,2,3,4,5,6};
cout << (sizeof (vet) / sizeof *(vet)) << endl;
return 0;
}
The most common way to get the size of a fixed-length array is something like this:
int temp[256];
int len = sizeof (temp) / sizeof (temp[0]);
// len == 256 * 4 / 4 == 256 on many platforms.
This doesn't work for dynamic arrays because they're actually pointers.
int* temp = new int[256];
int len = sizeof (temp) / sizeof (temp[0]);
// len == 4 / 4 == 1 on many platforms.
For a dynamic-length array if you care about the size, you're best off storing it somewhere when you allocate the array.
The problem with your loop, as pointed out by many is that you have an operator precedence problem here:
*temp + i
should be:
*(temp + i)
But the bigger problem, also pointed out above, is that you don't appear to understand pointers versus fixed-length arrays and are writing off the end of your array.
If you want to use array properly, you have to allocate enough memory for storing values. Once you specified its length, you can't change it. To know array size, you should store it in variable e.g.:
int n;
cin>>n;
int array = new int[n];
int array_length=n;
If you want to change array's length, best way is to use std container, for example std::vector.
Here is the answer to your question
int myarr [] = {1, 2, 3, 4, 5};
int length = sizeof(myarr) / sizeof(myarr[0]);
cout << length;
Because you only allocate space for an array of zero elements.
The following lines
temp [1] = 10;
temp[2] = '\0';
do not allocate more memory or resize the array. You are simply writing data outside the array, corrupting some other part of the application state. Don't do that. ;)
If you want a resizable array, you can use std::vector (and use the push_back member function to insert new values)
A vector also has the size() member function which tells you the current size.
If you want to use the primitive array, you have to track the size yourself. (and, when resizing the array is necessary, copy all elements from the old array to the new, larger one)
To get dynamic behavior in arrays, use a std::vector, or fall back on the old school c style using int * with manual memory allocation (new and delete)[*]
[*] C implementations (discussed in the context of character arrays as C dynamic string length) used malloc, realloc, and free, but these should be avoided in c++ code.
Try this out:
int length(int* temp)
{
int count = 0;
while (*temp != 0 && *temp != -858993460)
{
++count;
++temp;
}
return count;
}