This question already has answers here:
Accessing an array out of bounds gives no error, why?
(18 answers)
How do I find the length of an array?
(30 answers)
Closed 2 years ago.
int main()
{
int *array = new int; //Should provide space to store only one integer right?
for(int i =0; i < 10; i++)
{
cout << "Assigning" << i << "th value\n";
array[i] = i + 1;
}
for(int i = 0; i < 10; i++)
cout << array[i] << '\t';
delete array;
cout << '\n';
return 0;
}
Output
Assigning0th value
Assigning1th value
Assigning2th value
Assigning3th value
Assigning4th value
Assigning5th value
Assigning6th value
Assigning7th value
Assigning8th value
Assigning9th value
1 2 3 4 5 6 7 8 154274097 154405171
I know pointer size on my system is 8 bytes, checked with sizeof(int*) and integers take 4 bytes. I want to know how many chunks of memory in heap or free store (like literally boxes they use to teach students) does int* array = new int created, because books say I can store just one integer in it; to store more(like 10 ints) I need to do int* array = new int[10]. So how does this memory location pointed to by array can store 8 integers instead of one. Please note, I ran for loop 10 times as shown. Please tell me why are there just 2 garbage values, instead of 9 (since new should only allocate one integer worth space). Using Ubuntu with g++ 9.3.0.
int *array = new int; //Should provide space to store only one integer right?
Allocates a single int not an array.
for(int i =0; i < 10; i++)
{
cout << "Assigning" << i << "th value\n";
array[i] = i + 1;
}
Since there is no array but only a single element any access beyond the first (array[0]) array elements causes undefined behavior.
Any action, even formatting your hard drive, would be a valid program behavior.
Edit:
adapted to nearly completely rewritten question
Related
This question already has answers here:
Uninitialized variable behaviour in C++
(4 answers)
Closed 6 days ago.
int *arr = new int[3];
arr[0] = 1;
arr[2] = 3;
for (int i = 0; i < arr.size(); i++)
{
if(arr[i] exists/initialized) // what would be the condition?
std::cout << arr[i] << " ";
}
I'm trying to print elements from the array that are initialized, and ignore elements that aren't.
So, the above code would print out:
1 -1231409875 3
I want to fix this so that it outputs:
1 3
You cannot read from uninitilized elements, theirs values is indeterminate and reading them is undefined.
You can use a bool array of same size, initialize all its elements to false and every time you initialize something in the other array you set the corresponding element to true.
int* arr = new int[3];
bool* has_value = new bool[3]{};
arr[0] = 1;
has_value[0] = true;
arr[1] = 42;
has_value[1] = true;
for (size_t i= 0;i<3; ++i) {
if (has_value[i]) std::cout << arr[i] << " ";
else std::cout << "* ";
}
As mentioned in comments, if you use a contiguous portion of the array starting at the first element, it is sufficient to store the number of already initialized elements.
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.
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.
Can someone explain how an array of pointers implementation of c++ dynamically?
Is the below code correct?
If so,
int *ptr[5];
for (int i = 0; i < 5; i++)
{
int size = 2;
ptr[i] = new int [size] ;
//*(ptr + i) = new int[size]; this is the same as above line
cout << &ptr[i] << endl; ----------> line 1
cout << ptr[i] << endl; -----------> line 2
}
What is actually printing in line 1 and 2 ?
this is the addresses i get for line 1
0x7fff88f805d0
0x7fff88f805d8
0x7fff88f805e0
0x7fff88f805e8
0x7fff88f805f0
this is the addresses I get for line 2
0x55f946348ef0
0x55f946349330
0x55f946349360
0x55f946349390
0x55f9463493c0
Can somebody explain this whole mess of pointer arrays.
The picture provides a graphical explanation to the problem if anyone gets
confused with the array of pointers concept with dynamically allocating the array of pointers to new int or any other type array
int *ptr[2]; // statically declared pointer array stack
int p [2];
for (int i = 0; i < 2; i++)
{
int size = 2;
ptr[i] = new int[size];
cout << i << " array of int " << endl;
//*(ptr + i) = new int[size];
for (int j = 0; j < size; j++)
{
cout << "value : " ;
cout << *(ptr[i] + j) ; // <------- this should give 0's as value
//cout << (ptr[i])[j] ; <------ same thing
cout << " address :";
cout << ptr[i] + j << endl; //<----- these are in order as well since it's an array of type int
}
}
0 array of int
value : 0 address :0x564c9ede32c0
value : 0 address :0x564c9ede32c4
value : 0 address :0x564c9ede32c8
1 array of int
value : 0 address :0x564c9ede32e0
value : 0 address :0x564c9ede32e4
value : 0 address :0x564c9ede32e8
I am assuming you want to perform operation on dynamic array like adding element and printing;
Remember:In int *ptr=new int[5]; sizeof(ptr) is 8 bytes on stack memory and array will be stored in heap memory.
We will fetch the element via pointer ptr and every element will be fetched as per type of array (say int ) then ptr will go to 0th index element and read the data of it as int type (only 4 bytes as int is of 4 byte generally) and move to next index till end.
Look into code below:
#include <iostream>
using namespace std;
int main() {
int *ptr=new int[5]; //let size = 5
for(int i=0; i<5;i++){
cin>>ptr[i];
}
for(int i=0; i<5;i++){
cout<<&ptr[i]<<":"; //this will print every element's address per iteration
cout<<ptr[i]<<endl; //this will print every element as per input you gave
}
delete []ptr; //remember it's not delete ptr ask if required
return 0;
}
Now See the the output and dry run yourself you can understand
Output
0x556999c63e70:1
0x556999c63e74:2
0x556999c63e78:3
0x556999c63e7c:4
0x556999c63e80:5
Benefit of dynamic array is you can create dynamic sized array by taking size input as per user choice pass that variable is size of dynamic array
i.e you can change above size=5 to 'N' a variable one .
I think this might help you else you can ask for any further clarification.
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).