Looping using pointers and arrays [duplicate] - c++

This question already has answers here:
What happens if I increment an array variable?
(5 answers)
Increment operator on pointer of array errors?
(2 answers)
Closed 2 years ago.
I just got into learning pointers in C++ and I have been trying some different instances of using them to get a better understanding to them but there is some I go into that seems a little weird to me.
The code below is for looping through an array and what I assumed after it ran well that arr is just a pointer to the beginning of the array (because I could do ptr = arr;.
int size = 3;
int arr[size] = {50, 30, 20};
int *ptr;
ptr = arr;
for (int i = 0; i < size; i++) {
std::cout << *ptr << std::endl;
ptr++;
}
But When I try looping through the same array but with using arr instead of ptr without assigning it to arr it gave me an error (lvalue required as increment operand) referring arr++.
This is the Code.
int size = 3;
int arr[size] = {50, 30, 20};
for (int i = 0; i < size; i++) {
std::cout << *arr << std::endl;
arr++;
}
I don't understand why the first one work and the second doesn't although they are both pointers(as far as I know).

Related

when I call a function it returns a random valued array instead of the "right one" [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 12 months ago.
Improve this question
I'm trying to improve myself in competitive programming and I'm trying to do a easy task in a hard way.
I'm trying to split an array in two arrays (even and odd positions), apply the QuickSort on each of the two and then putting them together once again.
But I have some wrong output, probably I'm getting something wrong with pointers.
int arr[5] = {5, 4, 1, 3, 2};
int** a;
int size = sizeof(arr) / sizeof(arr[0]);
a = makearrs(arr, size);
Here's where I call the function makearrs passing it the array and the fixed size (I could pass 5 but I just calculated it).
Here's the function makearrs
int** makearrs(int* arr, int size){
int size_arr = size / 2;
int even_arr[size_arr + 1]; //[0, 1, 2, 3, 4]
int pair_arr[size_arr + 1];
// Inizializzo
for(int i = 0; i<=size_arr; i++){
even_arr[i] = 0;
pair_arr[i] = 0;
}
int j = 0;
for(int i=0; i<size; i = i+2){ //Lettura sicura, va bene per entrambi i casi.
pair_arr[j] = arr[i];
if(i+1 != size) {
even_arr[j] = arr[i + 1];
}
j++;
}
int ** a = makepairs(pair_arr, even_arr);
return a;
And finally the function makepairs which creates an array of pointers (two-sized) containing the two arrays (even and odd position array).
int** makepairs(int* arr, int* arr2) {
int** ptr = new int*[2];
ptr[0] = arr;
ptr[1] = arr2;
return ptr;
If I try to for-print the resulting
int * even;
even = a[1];
int * pair;
pair = a[0];
for(int i=0; i<3; i++){
cout << even[i];
cout << "\n";
cout << pair[i];
cout << "\n";
I get this output:
4
47398584
1
1
-325478504
47398584
You are returning pointers to the even_arr and pair_arr arrays. But as soon as the function returns, those arrays no longer exist. So it is an error to dereference the pointers to them.
int** makepairs(int* arr, int* arr2) {
int** ptr = new int*[2];
ptr[0] = arr;
ptr[1] = arr2;
return ptr;
So this allocates a new array and puts two values in it, each a pointer to an array. But:
int ** a = makepairs(pair_arr, even_arr);
return a;
Here you pass it pair_arr and even_arr, causing it to create an array with pointers to those two objects -- objects created locally on a stack that will be destroyed by the return statement immediately following.
Any attempt to dereference those pointers after the return is an error since they are pointers to arrays that no longer exist. (If you think they still exist, try to show where they were allocated and how they could be freed. It cannot be done.)
You should use std::vector instead to avoid this problem.
You are returning pointers to local variables. Those local variables cease to exist after your function returns, so the pointers are invalid. Any use of those pointers means your program has undefined behaviour.
Not only that, you don't have a C++ program.
int size_arr = size / 2;
int even_arr[size_arr + 1]; // This is not C++, size_arr needs to be a compile-time constant

How to properly delete pointer to an array in a C++ struct? [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Why can freed dynamically allocated memory still be accessed after a delete operation in C++? [duplicate]
(5 answers)
Closed 2 years ago.
I'm learning C++ from Stroustrop's A Tour of C++ 2E and I'm playing around with his examples.
I have a struct Vector, with a member elements that is a pointer to an array of doubles. I'm trying to delete[] the array which I allocated with new[], but even if there are no compile- or run-time errors, the array does not seem to be getting deleted. What's going on here?
#include <iostream>
struct Vector {
int size;
double* elements;
};
void print_array(double* first, int size) {
double* cursor = first;
for (int i = 0; i < size; ++i) {
std::cout << *cursor << " ";
++cursor;
}
std::cout << "\n";
}
int main() {
Vector v;
v.size = 5;
v.elements = new double[5];
for (int i = 0; i < v.size; ++i) {
v.elements[i] = 9-i;
}
print_array(v.elements, v.size);
delete[] v.elements;
std::cout << "v.elements==nullptr ? " << (v.elements==nullptr) << "\n";
print_array(v.elements, v.size);
return 0;
}
The output I'm getting is:
9 8 7 6 5
v.elements==nullptr ? 0
9 8 7 6 5
I do not yet know what will happen if I print out a deleted array, but I'm baffled as to why the third line in the output is happening at all. Thanks in advance.

Why size of c++ dynamic array is not changed? [duplicate]

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)
Closed 2 years ago.
Hi guys I tested c++ dynamic array and I changed 2 inputs every time.
but array size is not changed. Why?
#include <iostream>
using namespace std;
int main()
{
int r = 0;
int c = 0;
int cnt = 1;
cin >> r;
cin >> c;
int** arr1 = new int* [r];
for (int i = 0; i < r; i++)
{
arr1[i] = new int[c];
}
cout << sizeof(arr1) << endl;
cout << sizeof(arr1[0]);
}
I knew that If I entered two value 3 and 4 then results are 3 and 4
but the results are 4 and 4
You are testing the size of a pointer which is always 4 on 32 bit.
That's because sizeof is a compile time thing; it cannot determine an array size.
Generally arrays do not carry size information, that is why functions like strlen need a null terminator.
Suggestion: use std::vector.

Matrix size returns always 8 [duplicate]

This question already has answers here:
C++: getting the row size of a multidimensional array passed to a function
(6 answers)
Closed 7 years ago.
in the code below, I want to find the size of the 2d array(matrix), however, when I try to do that, eventhough I was declared the size of the matrix just before testing it, it always outputs 1. And size of the factorMatrix and factorMatrix[0] looks same as 8. Any idea what may be causing this? Thanks.
factorMatrix = new int* [3];
for(i=0; i<3; i++)
{
/**/
factorMatrix[i] = new int [1];
}
factorCountMatrix = new int* [3];
for(i=0; i<3; i++)
{
/**/
factorCountMatrix[i] = new int [1];
}
factorMatrix[0][0] = 2;
factorCountMatrix[0][0]= 0;
factorMatrix[1][0] = 3;
factorCountMatrix[1][0]= 0;
factorMatrix[2][0] = 5;
factorCountMatrix[2][0]= 0;
//test = checkFactorMatrix(3);
test = (sizeof(factorCountMatrix) / sizeof(factorCountMatrix[0]));
cout << test << endl << endl;
When you use the sizeof operator on a pointer, you get the size of the pointer, and not what it points to. You need to keep track of the size of the memory you allocate yourself, or use something else like std::array or std::vector (which I recommend).

Why creating a string affect other variables? [duplicate]

This question already has answers here:
How to access a local variable from a different function using pointers?
(10 answers)
Closed 7 years ago.
I have the following code.
int *x = somefuction();//return array of two elements
string s;
cout << x[0] << " and " << x[1];
This code prints unexpected values. But if I comment out "string s;" row it works fine. What is the reason?
Some function is:
int* getRowCol(int l){
int min = floor(sqrt(l));
int max = ceil(sqrt(l));
int area = 100000;
int result[2];
for (int col = min; col <= max; col += 1){
for (int row = min; row <= col; row += 1){
if (col*row < area && row*col>=l){
area = row*col;
result[0] = row;
result[1] = col;
}
}
}
return result;
}
You are returning a pointer to some value that exists on the stack in someFunction(). I.e. a local variable. These don't live past the end of the function call.
int* someFunction()
{
int someInts[2] = {10, 20}; // only exists inside someFunction
return someInts;
}
Perhaps you should use a std::vector, which will take care of allocating memory in a way that is safe to use like this.
It is Undefined Behaviour to dereference this returned pointer in any way. Your code could do absolutely anything.
Try something like this instead:
std::vector<int> someFunction()
{
std::vector<int> someInts {10, 20};
someInts.push_back(30);
return someInts;
}