Truncate the last few elements of an array - c++

I am new to C and C++, please help me in getting the required solution. I have used memcpy to copy the contents of 'array' to 'arr'. But since the size of 'arr' is 10, it appends 0 to the remaining elements. How can I truncate the 'arr' to size 5.
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
uint8_t array[5] = {1,2,3,4,5};
uint8_t arr[10] = {0};
memcpy( arr, array, 5);
for (auto e: arr){
cout << e << " ";
}
return 0;
}
Output for the above code: 1 2 3 4 5 0 0 0 0 0
required output : 1 2 3 4 5

You cannot truncate the size of the static array after compilation. If you were using some other data structure like vector from C++ STL then the size of that container object might have been variable.

Instead of
for (auto e: arr){
cout << e << " ";
}
you can keep array's size in a variable and cout arr that times, like:
int i, arraySize = 5;
for (i=0; i<arraySize; i++) {
cout << arr[i] << " ";
}

Best Practice is to create a pointer and free the memory or second way is to don't allow kernel to give memory to you create custom memory allocator and assign it to your array

Related

I wanted to reverse my array. Why this code gives garbage value?

#include <iostream>
using namespace std;
int main(){
int n;
int a[n];
cin>>n;
for(int i=0;i<n;i++){
cin>>a[i];
}
for(int i=n;i>=0;i--){
cout<<a[i]<<" ";
}
}
Input:- 4
1 2 3 4
Output 4199008 4 3 2 1
For starters the program has undefined behavior because the variable n is not initialized
int n;
So this declaration
int a[n];
is invalid. Moreover variable length arrays is not a standard C++ feature. Instead use the standard class template std::vector.
Also within this loop
for(int i=n;i>=0;i--) {
cout<<a[i]<<" ";
}
you are trying to access of non-existent element with the index n.
Also you are not reversing an array. You are trying to output an array in the reverse order.
Pay attention to that there are standard algorithms std::reverse and std::reverse_copy declared in the header <algorithm>.
Here is an example how your program with using your approach could look
#include <iostream>
#include <vector>
int main()
{
size_t n = 0;
std::cout << "Enter the size of an array ";
std::cin >> n;
std::vector<int> v( n );
std::cout << "Enter " << n << " elements: ";
for ( auto &item : v ) std::cin >> item;
std::cout << "The array in the reverse order\n";
for ( size_t i = v.size(); i != 0; )
{
std::cout << v[--i] << ' ';
}
std::cout << '\n';
return 0;
}
The program output might look like
Enter the size of an array 10
Enter 10 elements: 0 1 2 3 4 5 6 7 8 9
The array in the reverse order
9 8 7 6 5 4 3 2 1 0
If to use standard algorithms then your program can look the following way
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
size_t n = 0;
std::cout << "Enter the size of an array ";
std::cin >> n;
std::vector<int> v( n );
std::cout << "Enter " << n << " elements: ";
std::copy_n( std::istream_iterator<int>( std::cin ), n, std::begin( v ) );
std::cout << "The array in the reverse order\n";
std::reverse_copy( std::begin( v ), std::end( v ),
std::ostream_iterator<int>( std::cout, " ") );
std::cout << '\n';
return 0;
}
The program output might look the same way as shown above
Enter the size of an array 10
Enter 10 elements: 0 1 2 3 4 5 6 7 8 9
The array in the reverse order
9 8 7 6 5 4 3 2 1 0
a[n] will return the element after the last one. When you iterate in reverse order, start with i=n-1.
At the beginig of your program there is a mistake:
int n; // You declare n with no value
int a[n]; // You use is
cin>>n; // After you used it you get your value-
Now i can suppose that that was just an error while copying it because you give inputs and outputs
Input:- 4 1 2 3 4 Output 4199008 4 3 2 1
So forgeting about that, you declare an array of size n. Remember that the elemnts of the array will go from 0 to n-1. Now look at your second for loop
// the first element you acces is n and you stop at 1
// but the array goes from n-1 to 0
for(int i=n;i>=0;i--){
cout<<a[i]<<" ";
}
So you still get n values as an output but the first element that you access is outside of the array. Thats why you get a garbage value, that is a value that was left there.
A solution will be to change the for loop
for(int i=n-1;i>=-1;i--){
cout<<a[i]<<" ";
}
While reversing the array start the loop from n-1 that is i=n-1 (n is the no of elements in array). And run the loop till i>=0. If you will start loop from n it will read illegal index which is out of range and will give you garbage value.
for(int i=n-1; i>=0; i++){
cout<<arr[i]<<" ";}

Creating array of pointers using input from stdin

I understand how to create it in general. For example:
int ar1[3] = {1, 2, 3};
int ar2[4] = {4, 5, 6, 7};
int* ar[2] = {ar1, ar2};
cout << *(ar[1]+2);
will output:
6
Now, I would like to create the same array using cin. The format of the input is the following. The first line stores the number of arrays n. The other n lines store first the number of elements in the array, and then the elements of the arrays. For example:
2
3 1 2 3
4 4 5 6 7
To parse the input and create the array I have the following code:
int n;
cin >> n;
cout << "The number of variable-length arrays: " << n << endl;
int* ar [n];
for (int k = 0; k < n; k++){
cout << "..reading the array number: " << k + 1 << endl;
int n_el; cin >> n_el;
cout << "The array contains " << n_el << " elements." << endl;
int ar_k [n_el];
for (int j = 0; j < n_el; j++) {
cin >> ar_k[j] ;
}
ar[k] = ar_k;
for (int j = 0; j < n_el; j++) {
cout << *(ar[k] + j) << endl;
}
}
Which outputs:
The number of variable-length arrays: 2
..reading the array number: 1
The array contains 3 elements.
1
2
3
..reading the array number: 2
The array contains 4 elements.
4
5
6
7
However, if I try to access the arrays outside the loop, it does not work. Given the code:
for (int j = 0; j < 3; j++) {
cout << *(ar[0] + j) << endl;
}
the output is:
4
32766
44613906
I guess it happens because as soon as you are out of the loop, the memory where the arrays are stored gets freed. How to prevent this? Or should I use a different approach to solve the task?
You are right, the memory is getting freed when you exit the loop.
Also your code is illegal int* ar [n]; where n is a variable is not legal C++. Even though your compiler accepts it (another compiler would not).
One other approach is to use dynamic memory allocation using new. Replace
int* ar [n];
with
int** ar = new int*[n];
and
int ar_k [n_el];
with
int* ar_k = new int[n_el];
The point of dynamic allocation is that the memory doesn't get freed until you delete it.
Dynamic memory allocation is a big topic, and this answer just scratches the surface. Time for some reading.

How to access elements of array and vector repeatedly in c++?

I have a vector of int V'
vector<int> V={2,4,5,6,7};
I want to iterate through vector such that if index is greater than size of vector it should return again some element in vector for example V.size() is 5 if I enter V[6] I need result to return 4,if I enter v[5] it should return 2.....
can I also do it with arrays??
Thanks in advance..
If you want accessing the values to "wrap around", then simply use the modulo operator when indexing.
That is to say: instead of V[i], use V[i % V.size()].
For array[]={2,4,5,6,7};
If you want to circle through array you could use index mod sizeofarray.
Let n be the index
//here size of array =5;
You could use array[n% 5] to acces elements.
so array[6] => array[6 % 5] => array[1]= 4
and same applies with vector.
Here's a solution that prompts for user input until the user inputs a number within the boundaries of the array...
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vec{1, 3, 5, 7, 9}; // size 5
int num = 0;
do {
cout << "Enter a number between 0 and " << vec.size() - 1 << ": ";
cin >> num;
} while (num < 0 || num >= vec.size());
cout << "The vector value is: " << vec[num] << endl;
return 0;
}

The vector of random integers cannot be printed, C++

I wrote a simple program to generate a vector of random numbers. I tried to print each element in the vector but the output doesn't seem correct. For example, I push_back 5 numbers but the vector.size() gives 10... I have no idea why. Please help.
#include <iostream>
#include <vector>
#include <time.h>
#include <cstdlib>
using namespace std;
int main()
{
srand(time(NULL));
vector<int> arr(5);
int i, val;
for (i=0; i<5; i++)
{
val = rand()%30;
cout << "value " << i << " is " << val << endl;
arr.push_back(val);
}
for (i=0; i<arr.size() ; i++){
cout << arr[i] << " " << arr.size() << endl;
}
return 0;
}
OUTPUT:
value 0 is 2
value 1 is 13
value 2 is 9
value 3 is 28
value 4 is 27
0 10
0 10
0 10
0 10
0 10
2 10
13 10
9 10
28 10
27 10
In line
vector<int> arr(5);
you already allocated 5 entries. You can access them without pushing back new elements. eg:
vector<int> arr(5);
arr[1];
is valid and won't crash.
Now if you do additional push_back you will extend existing vector, so it will change its size.
vector<int> arr(5);
This creates a vector of 5 elements.
arr.push_back(val);
This appends one new element to the vector. So the first time it is called, the vector will now contain 6 elements.
The vector constructor you are using, creates a vector with 5 values (equal to 0) already present in it. If you want to make the vector allocate space for 5 elements (as I am assuming - your plan). You can create a vector with a default constructor and then use the reserve method.
instead of
vector<int> arr(5);
It should read
vector<int> arr;
arr.reserve(5);

How do I fix the size of my array?

everyone. I am struggling with understanding why my numbers variable keeps outputting 1. I am trying to double the size anytime the number of elements is equal to the size of the array but I end up not getting anywhere near that part of my code.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int selection;
int size = 2;
// Initializing the array
int *dArray;
int v = 0;
int i, j, temp;
dArray = new int[size];
dArray[0] = 2;
dArray[1] = 3;
int numbers = sizeof(dArray) / sizeof(dArray[0]);
do {
// Printing the menu
cout << "1) Print Elements" << endl;
cout << "2) Add Element" << endl;
cout << "3) Delete Element" << endl;
cout << "4) Return Size" << endl;
cout << "5) Exit" << endl;
cout << "Enter your selection number: ";
cin >> selection;
switch (selection)
{
case 1:
// Outputting the elements
for (int i = 0; i < size-1; i++)
{
cout << dArray[i] << ", ";
}
cout << dArray[size - 1] <<endl;
cout << numbers << endl;
break;
case 2:
// Asking for another element
cout << "What number shall be put into the array? \n";
cin >> v;
if (numbers== size)
{
// If the size is too small...
int *nArray = new int[2 * size];
for (int i = 0; i < size; ++i)
{
nArray[i] = dArray[i];
}
delete[] dArray;
dArray = nArray;
// Finished creating a new array
cout << "Array size expanded to " << 2 * size << endl;
// Adding the element
dArray[size] = v;
size = 2 * size;
// Sorting the elements
for(i=0;i<numbers;i++)
{
for(j=i+1;j<numbers;j++)
{
if(dArray[i]>dArray[j])
{
temp =dArray[i];
dArray[i]=dArray[j];
dArray[j]=temp;
}
}
}
}
else
{
// Adding the element
dArray[size] = v;
size = 2 * size;
// Sorting the elements
for(i=0;i<numbers;i++)
{
for(j=i+1;j<numbers;j++)
{
if(dArray[i]>dArray[j])
{
temp =dArray[i];
dArray[i]=dArray[j];
dArray[j]=temp;
}
}
}
}
break;
}
} while (selection!= 5);
cin.get();
cin.ignore();
return 0;
}
Does anyone know why the sizeof function keeps acting this way?
This is not the size of your array. It's the size of a pointer, divided by the size of an int.
int numbers = sizeof(dArray) / sizeof(dArray[0]);
This is the size of the array in your program.
int numbers = size;
sizeof(dArray) gives you the size of dArray. dArray is defined as int *dArray, so its size is sizeof(int*). That doesn't change, regardless of what the pointer points to. That's different from an actual array; your size code would work correctly with int dArray[3];.
To get the size of the array, just use your size variable; that's the number of int objects that were allocated.
Even better, use std::vector<int>; its size() member function tells you how many elements it has.
int numbers = sizeof(dArray) / sizeof(dArray[0]);
Numbers is resolving to 1 because dArray is a pointer to the start of your array, not the array itself. When you call sizeof() you are getting the size of the pointer, not the array. On a 32 bit application, the pointer is 32 bits (4 bytes) and your first int is also 32 bits (4 bytes). So what this statement resolves to is
int numbers = 4 / 4;
leaving 1. If you instead declared an array of doubles then sizeof(dArray[0]) would be 8 but the size of the pointer would still be 4, so the statement would resolve to numbers = 4 / 8 = .5, but since numbers is an int it would just resolve to 0. So your code would still break, but in new exciting ways.
Interestingly enough, if you compiled this as a 64 bit application sizeof(dArray) would be 64 bits (8 bytes), so you would get numbers = 8 / 4 = 2 as you expected. Then you would double your array size and your code would break because numbers would resolve to 2 which would potentially be even more confusing, so be thankful you caught it now!
I agree with what others have said though. If you use a Vector you can just keep pushing values onto the end of it and let it worry about changing the size of the array!