Creating links between arrays of pointers in C++? - c++

how can I create links between two arrays of pointers in C++.
I (obviously) tried the method where I declared 2 pointer Arrays and started equating their indexes individually but C++ would give me an error (stating: cannot convert int* to int**).
So...any solutions?
For a better understanding of the question, look at this link:
QUESTION
EDIT:
Here's a simple breakdown code that I tried (but it didn't work at all):
#include<iostream>
using namespace std;
int main ()
{
int *A[4];
int *B[4];
A[0] = &B[1];
}

From the picture in your description, it seems that only elements of A need to point to elements of B. This means B can just be a regular array of ints:
int *A[4];
int B[4];
A[0] = &B[1];

Related

How to find the highest number of passenger of all round?

im a new problem solver. recently i came across this problem on codeforces website. i managed to get the two values required for each turn depending on the number of turn given by the user, but i cant find the highest number of passenger at stop out of all.
#include <iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
int turn,get_off,get_on,total_passenger,highest_total;
cin>>turn;
int* stops=new int(turn);
for(int i=0;i<turn;i++){
cin>>get_off>>get_on;
total_passenger=get_on-get_off;
stops[i]=total_passenger;
}
for(int i=0;i<turn;i++){
if(stops[i]>stops[i+1]){
highest_total=stops[i];
}
}
cout<<highest_total<<endl;
return 0;
}
you can try using https://en.cppreference.com/w/cpp/algorithm/max_element
also you set the total passengers number to the difference between get off and get on and I think you should just add that difference, and to allocate memory for int* you use [] instead of ()
#include <iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
int turn,get_off,get_on,total_passenger,highest_total;
cin>>turn;
int* stops=new int[turn];
for(int i=0;i<turn;i++){
cin>>get_off>>get_on;
total_passenger+=get_on-get_off;
stops[i]=total_passenger;
}
cout<<std::max_element(stops, stops + turn)<<endl;
}
The issue seems to be with int *stops = new int(turn). It will allocate memory for 1 integer.
Use int stops[turn] and your algorithm need to be modified.
stop[i] += total_passenger need to be used with some if-else.
You can initiate stops as an array I guess(int stops[turn]) as C++ now offers to allocate memory this way even inside any function. That may solve your problem.
Alongside you will have to check corner cases as your highest_total variable may provide garbage value. So while declaring the variable assign a value to it. I prefer initializing int highest_total=-1 here.
Actually you dont need an array or pointer here. This can be solved this way-
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
int turn,get_off,get_on,total_passenger=0;
cin>>turn;
int highest_total=-1;
for(int i=0;i<turn;i++){
cin>>get_off>>get_on;
total_passenger=total_passenger+get_on-get_off;
if(total_passenger>highest_total)
highest_total=total_passenger;
}
cout<<highest_total<<endl;
return 0;
}
Firstly: int* stops=new int(turn); initializes a pointer to a new int with the value turn. See int a = 0 and int a(0) differences
Instead you should either use int* stops=new int[turn];, read about when you should use new here: When should I use the new keyword in C++?. An important note is that you have to delete the variable in order to avoid a Memory leak.
Or (which I would say is the case you should use in this scenario), int stops[turn];.
Besides that I can not argue with your logic since I believe this is not a forum to help you solve code, although the syntax seems correct.
I would recommend reading Why is "using namespace std;" considered bad practice? if you are interested in learning C++ though.

array declaration in runtime and compile time

Please look at the following 2 program segments:
int a,b;
cin>>a>>b;
int arr1[a*b];
int arr2[a];
now if i give input value of 'a' = 100000 and 'b' = 5, program shows runtime error because of memory overflow I think. Now look to the other segment of code:
int arr1[500000];
int arr2[100000];
Now when I declare array of same size as shown in above code, The program works fine. Why is that so?
Now when I declare array in advance of same size I declared at runtime, The program works fine. Why is that so?
Because variable length arrays (aka VLAs) aren't valid standard c++ code.
If you need such thing allocated at runtime the idiomatic c++ way is to use a std::vector:
int a,b;
cin>>a>>b;
std::vector<int> arr1(a*b);
std::vector<int> arr2(a);

Correct pointer arithmetic in C

I am trying to learn pointer manipulation in C, and I am not understanding how part of the code isn't working.
#include <stdio.h>
int main() {
int *alpha[17];
*(alpha+4)= 35;
*(alpha+5)= 35;
*(alpha+12)= 50;
printf("%d", *(alpha+4));
*(alpha+8)=*(alpha+5) + *(alpha+12);
return 0;
}
Why is the line after the printf not working, and causing a crash, when the previous lines ran perfectly? I am trying to get the 9th value to equal the sum of the 6th and 13th value.
int *alpha[17]; creates array of pointers.
If you want array of int, use int alpha[17];
Your assignations are succesful because of implicit cast from int to pointer. (I hope you are getting warnings)
Adding two pointers is not only non-sensical, but also not allowed in C.
This post covers why adding two pointers is forbidden in C++, but arguiments are applicable to C also.
You have created an array of pointers but have not array of ints.
You should use:
int alpha[17];

I got a trouble with C++ array initialization

I am new to C++. Recently, I have been stuck with a simple code of C++ features. I will be very grateful if you can point out what exactly the problem. The code as follows:
// used to test function of fill
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
int val = 0;
int myarray[8];
//fill(myarray,myarray+2,1);
for(;val < 8;++val){
cout << myarray[val];
cout << endl;
}
}
And the it has printed out:
-887974872
32767
4196400
0
0
0
4196000
0
The question is I thought the default value for array without initialization (in this case its size is 8) would be (0,0,0,0,0,0,0,0). But there seemed to be some weird numbers there. Could anyone tell me what happened and why?
The elements are un-initialized, i.e, they contain garbage value.
If you want to initialize the array elements to 0, use this:
int myarray[8] = {};
Initial values are not guaranteed to be 0.
If you want to get a array have a initial value,you can do like this:
int *arr = new int[8]();
int myarray[8];
This is a simple declaration of an Array i.e you are telling the compiler "Hey! I am gonna use an integer array of size 8". Now the compiler knows it exists but it does not contail any values. It has garbage values.
If you intend to initialize array (automatically) then you need to add a blank initialization sequence.
int myarray[8]={}; //this will do
Happy Coding!

use array in structure c++

I have a struc like this:
struct process {int PID;int myMemory[];};
however, when I try to use it
process p;
int memory[2];
p.myMemory = memory;
I get an criptic error from eclipse saying int[0] is not compatible with int[2];
what am i doing wrong?
Thanks!
Don't use static arrays, malloc, or even new if you're using C++. Use std::vector which will ensure correct memory management.
#include <vector>
struct Process {
int pid;
std::vector<int> myMemory;
};
Process p;
p.reserve(2); // allocates enough space on the heap to store 2 ints
p.myMemory.push_back( 4815 ); // add an index-zero element of 4815
p.myMemory.push_back( 162342 ); // add an index-one element of 162342
I might also suggest creating a constructor so that pid does not initially have an undefined value:
struct Process {
Process() : pid(-1), myMemory() {
}
int pid;
std::vector<int> myMemory;
};
I think you should declare myMemory as an int* then malloc() when you know the size of it. After this it can be used like a normal array. Int[0] seems to mean "array with no dimension specified".
EXAMPLE:
int *a; // suppose you'd like to have an array with user specified length
// get dimension (int d)
a = (int *) malloc(d * sizeof(int));
// now you can forget a is a pointer:
a[0] = 5;
a[2] = 1;
free((void *) a); // don't forget this!
All these answers about vector or whatever are confused :) using a dynamically allocated pointer opens up a memory management problem, using vector opens up a performance problem as well as making the data type a non-POD and also preventing memcpy() working.
The right answer is to use
Array<int,2>
where Array is a template the C++ committee didn't bother to put in C++99 but which is in C++0x (although I'm not sure of the name). This is an inline (no memory management or performance issues) first class array which is a wrapper around a C array. I guess Boost has something already.
In C++, array definition is almost equal to pointer constants, meaning that their address cannot be changed, while the values which they point to can be changed. That said, you cannot copy elements of an array into another by the assignment operator. You have to go through the arrays and copy the elements one by one and check for the boundary conditions yourself.
The syntax ...
struct process {int PID;int myMemory[];};
... is not valid C++, but it may be accepted by some compilers as a language extension. In particular, as I recall g++ accepts it. It's in support for the C "struct hack", which is unnecessary in C++.
In C++, if you want a variable length array in a struct, use std::vector or some other array-like class, like
#include <vector>
struct Process
{
int pid;
std::vector<int> memory;
};
By the way, it's a good idea to reserve use of UPPERCASE IDENTIFIERS for macros, so as to reduce the probability of name collisions with macros, and not make people reading the code deaf (it's shouting).
Cheers & hth.,
You cannot make the array (defined using []) to point to another array. Because the array identifier is a const pointer. You can change the value pointed by the pointer but you cannot change the pointer itself. Think of "int array[]" as "int* const array".
The only time you can do that is during initialization.
// OK
int array[] = {1, 2, 3};
// NOT OK
int array[];
array = [1, 2, 3]; // this is no good.
int x[] is normally understood as int * x.
In this case, it is not, so if you want a vector of integers of an undetermined number of positions, change your declaration to:
struct process {int PID;int * myMemory;};
You should change your initialization to:
int memory[2];
p.myMemory = new int[ 10 ];