I am newly to programming with c++ and I am trying to allocate memory for array of struct. The problem is I don't know the size of elements inside it at compile time. I want the "empty" part to be allocated with null pointers. I run this code below, but there is no the output I expected to be. Could somebody help me?
#include <iostream>
using namespace std;
typedef struct ones{
int a;
int b;
}ones;
ones** twoes = nullptr;
int main()
{
cout<<"Hello World";
for(int i = 0; i < 5; i++)
{
twoes[i]= nullptr;
}
cout<< "i dont get HERE" << endl;
for(int i = 0; i < 5; i++)
{
twoes[i]= new ones;
twoes[i]->a = 2;
cout<< twoes[i]->a <<endl;
}
return 0;
}
I'm trying to understand pointers in C++ by writing some examples. I tried creating a pointer array and when I was trying to add integers to it does not work properly. I want to add integers from 0 to 9 to pointer array and print it.
int *array;
array = new int[10];
for(int i=0; i<10; i++){
*array[i] = i;
cout<<*array<<endl;
}
The following will do what you've described:
#include <iostream>
int main()
{
int* array = new int[10];
for (int i = 0; i < 10; ++i)
{
array[i] = i;
std::cout << array[i] << std::endl;
}
delete [] array;
return 0;
}
However in modern C++ the idomatic solution would be something like this:
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v;
for (int i = 0; i < 10; ++i)
{
v.push_back(i);
std::cout << v[i] << std::endl;
}
return 0;
}
You allocated memory for 10 integers for pInt but do not allocate any memory for array. Since array doesn't have any memory allocated it can not hold data. One solution is to just use your pInt variable. On that note where you have *array[i] = i; there is no need to dereference with * as having the brackets [] dereference the pointer. So you can replace that line with pInt[i] = i; then if you call cout << *pInt; you would get the first value in the array. You can cout each in a for loop like cout << pInt[i]; One final thing that you may already know but just incase, whenever you use pointers and allocate memory by using new make sure you deallocate that memory when you are done to prevent memory leaks. For this you would do delete[] pInt;
Allocate something in array otherwise how do you expect it to hold something.(unless you point it to some already allocated memory).
Or assign array=pInt and then you can use it to hold values. array[i]=i
An example:
#include <iostream>
using namespace std;
int main()
{
int *a;
// int *b;
// b= new int[10]; we can simply allocate it to 'a' directly
// a = b;
a = new int[10];
for(int i=0;i<5;i++)
a[i]=i;
for(int i=0;i<5;i++)
cout<<a[i];
delete[] a;
return 0;
}
The pointer variable is nothing but address holder. So here a is not
holding anything significant before initializing. But once you
initialize it either by allocating new or assign it to something
similar it just doesn't point to nowhere. And once you do that you
have some chunk of memory which you can access by that pointer which
is what i did here. What if I didn't initialize and tried to use a.
it's Undefined behavior.
Don't use bits/stdc++.h Link. It might help you write small code but it should never be used in development or production level code.
You should declare a variable as
int *array=new int;
try this
int *array=new int;
int *pInt = new int[10];
for(int i=0; i<10; i++){
*array = i;
cout<<*array<<endl;
}
and if you want to display array from 0 to 9
try this
int *array=new int[10];
int *pInt = new int[10];
for(int i=0; i<10; i++){
array[i] = i;
cout<<array[i]<<endl;
}
for Adding of array
try this
int *array=new int;
int *pInt = new int[10];
for(int i=0; i<10; i++){
pInt[i]=i;
cout<<pInt[i]<<endl;
*array=*array+pInt[i];
}
cout<<"Addition ="<<*array;
return 0;
I wrote two functions - one to create two-dimentional double array, and another one to delete it.
double** createMatrix(int n)
{
double **a = new double *[n];
for (int i=0; i < n; i++)
a[i] = new double[n];
return a;
}
void deleteMatrix(double** a, int n)
{
for (int i=0; i < n; i++)
delete [] a[i]; // ERROR HERE
delete []a;
}
Allocated array is working fine. But when I try to free it, I get an error (on a marked line): "project2.exe has triggered a breakpoint.".
I'm using Visual Studio 2012.
edit:
I created a full program:
int main()
{
const int n = 10;
double **m = createMatrix(n);
deleteMatrix(m, n);
return 0;
}
And it's working fine. Also, I found my problem. It was a typo in copyMatrix function.
for (int j=0; j <= n; j++) // should be < instead of <=
a[i][j] = originalMatrix[i][j];
Thanks a lot for your help!
The obvious solution is not to use an array in the first place.
How to create an n x n matrix ?
#include <iostream>
#include <vector>
using Row = std::vector<int>;
using Matrix = std::vector<Row>;
int main() {
size_t const n = 5;
Matrix matrix(Row(n), n);
}
Simple right ? And as a bonus, copy, move and destruction are provided free of charge.
My weekend assignment was to make a function that gets an array of integers and the size of the array, and creates an array of pointers so that the pointers will be sorted using bubble sort (without changing the original array).
While debugging I found out that it works just fine, but when the function goes back to main() the pointers array gets initialized and everything's gone.
#include <iostream>
using namespace std;
void pointerSort(int arr[], int size, int* pointers[]);
void swap(int a, int b);
void main()
{
int arr[5]={7,2,5,9,4};
int size = 5;
int* pointers[5];
pointerSort(arr, size, pointers);
for (int i = 0; i < 5 ; i++)
cout << *pointers[i] << endl;
}
void pointerSort(int arr[], int size, int* pointers[])
{
int j, i;
bool change = true;
pointers = new int*[size];
for (i = 0; i < size; i++)
pointers[i] = &arr[i];
i = 0;
j = 1;
while (i <= size-1 && change == true)
{
change = false;
for (i = 0; i < size-j; i++)
{
if (*pointers[i] > *pointers[i+1])
{
swap(pointers[i], pointers[i+1]);
change = true;
}
}
j++;
}
}
void swap(int&a, int&b)
{
int temp;
temp = a;
a = b;
b = temp;
}
pointers = new int*[size];
At this point pointers is already an array of pointers, no allocation is needed.
After this line pointers IS NO LONGER THE ARRAY IN YOUR MAIN FUNCTION.
This is why your function is failing, because you are reassigning the array to which pointers is pointing to. The original array ISNT getting reinitialized, its just ignored throughout the entire code.
It is also a memory leak as ATaylor mentions, since you do not delete the allocated space, and cannot delete the space after the function finishes.
To fix everything: just remove the above line.
#include <iostream>
using namespace std;
class SomeClass {
public:
bool someArray[4][4]={{0,0,0,0},{0,0,0,0}};
};
int main()
{
SomeClass super;
super.someArray={{1,1,1,0},{1,0,0,1}}; //This goes red, indicates a mistake. How do i properly fill it?
for (int i=0;i<4;i++){
for (int j=0;j<4;j++){
cout<<super.someArray[i][j];
}
cout<<endl;
}
return 0;
}
Please see the comments in the code above.
By the way: super.someArray[4][4]={{1,1,1,0},{1,0,0,1}}; doesn't work either and it probably shouldn't.
You probably mean to use bool someArray[2][4] (i.e, an array with two elements that contains arrays with four boolean elements).
You can't assign one array into another in C++; you'll need to copy the individual elements. I.e., something like:
super.someArray[0][0] = 1;
super.someArray[0][1] = 1;
super.someArray[0][2] = 1;
super.someArray[0][3] = 0;
super.someArray[1][0] = 1;
super.someArray[1][1] = 0;
super.someArray[1][2] = 0;
super.someArray[1][3] = 1;
(If you have some source for your data, you could use a loop of course.)
The following worked for me using the GNU compiler. Notice that I replaced your raw array with std::tr1::array. This class is more flexible with respect to assigning entire arrays (as opposed to just initializing arrays from literals).
#include <iostream>
#include <tr1/array>
using namespace std;
using namespace tr1;
typedef array<array<bool,4>,4> array4x4;
class SomeClass {
public:
array4x4 someArray;
SomeClass() : someArray((array4x4){{{{0,0,0,0}},{{0,0,0,0}}}}) {}
};
int main()
{
SomeClass super;
super.someArray=(array4x4){{{{1,1,1,0}},{{1,0,0,1}}}}; //Now works
for (int i=0;i<4;i++){
for (int j=0;j<4;j++){
cout<<super.someArray[i][j];
}
cout<<endl;
}
return 0;
}
However, the following approach is a bit closer to where you started, and demonstrates some of the things suggested in other comments...
#include <iostream>
#include <algorithm>
using namespace std;
class SomeClass {
public:
bool someArray[4][4];
SomeClass()
{
bool temp[4][4] = {{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}};
for ( int j=0; j<4; j++ ) for ( int i=0; i<4; i++ ) someArray[j][i] = temp[j][i];
}
};
int main()
{
SomeClass super;
bool temp[4][4] = {{1,1,1,0},{1,0,0,1}}; // a local source of data
for ( int j=0; j<4; j++ ) for ( int i=0; i<4; i++ ) super.someArray[j][i] = temp[j][i];
for (int i=0;i<4;i++){
for (int j=0;j<4;j++){
cout<<super.someArray[i][j];
}
cout<<endl;
}
return 0;
}
super.someArray[4][4]={{1,1,1,0},{1,0,0,1}};
The line above just needs to be:
super.someArray[4][4]={1,1,1,0,1,0,0,1};
Explaination:
it will automatically go the next section of the array. If you think of it as a table, once the first row is filled up, it will start declaring it for the next row.
So if you wrote:
super.someArray[4][4]={1,1,1,1,1};
it would set:
someArray[0][0]
someArray[0][1]
someArray[0][2]
someArray[0][3]
someArray[1][0]
all equal to 1.
(I might have the numbers switched so it could be x and y places are changed, I can't recall for c++)