How do I get an address of an array inside a struct? - c++

I’m trying to get a pointer to an array that’s in a struct, but doing *(struct->array) gives me an error.
Here’s the code:
#include <iostream>
using namespace std;
struct Numbers {
int highest;
int lowest;
int list[10];
};
void print_pointer_to_first_number(const Numbers* num) {
cout << num.list << endl;
}
int main() {
Numbers numbers;
numbers.highest = 10;
numbers.lowest = 1;
print_pointer_to_first_number(numbers);
return 1;
}
I’m getting an error saying:
error: member reference type 'const Numbers *' is a pointer; did you mean to use '->'?
I am not allowed to change the argument in the function.

You'll want to pass Numbers as reference rather than a pointer (essentially the same, but with nicer syntax):
void print_pointer_to_first_number(const Numbers &num)
Alternatively you can keep it as a pointer, but then you'll need to (1) dereference it properly:
num->list
and (2) pass a pointer when you call it:
print_pointer_to_first_number(&numbers)

Related

Shakersort c++, error: invalid conversion from ‘int’ to ‘int* - I can't find where I mixed integer and pointer to integers

#include <iostream>
using namespace std;
const int up=18;
int realArray[up]={12,28,75,16,66,6,121,19,195,56,108,221,19,93,104,127,73,22}; //definition of a random array
void shakersort(int formArray[up]);//shakersort declared
void tauschen(int *a,int *b){int zw= *a; *a=*b; *b=zw;}
int main()
{
shakersort(realArray[up]); //here happens the error of the conversion
return 0;
}
void shakersort(int formArray[up]){ //the code
for(int i=0; i<up/2;i++){
for (i=0; i<up-1;i++){
if(formArray[i]>formArray[i+1]){
tauschen(&formArray[i], &formArray[i+1]);
}
}
for (int k=up-1; k>0;i--){
if(formArray[k]>formArray[k-1]){
tauschen(&formArray[k], &formArray[k-1]);
}
}
}
}
Not sure why there is a conversion error. Used the same code at declaration and application so not sure why it's not working.
up is an int with value 18 so in this line
shakersort(realArray[up]);
you are basically writing
shakersort(realArray[18]);
which will index a single value from your array (which also happens to be out of bounds, which would therefore be undefined behavior). Instead just pass the array itself
shakersort(realArray);
though I would encourage you to look into using std::vector instead
void shakersort(std::vector<int>& formArray);
so you don't need a global variable floating around to determine the array size, you can just use formArray.size()

C++ how to pass string array in function and assign to a variable?

I got this error while coding a simple function. This is my function specification.
string studentName;
string courseTaken[3];
void setStudent(string, string[]);
void Student::setStudent(string n, string a[])
{
studentName= n;
courseTaken = a;
}
This is the error I have gotten:
incompatible types in assignment of string* to string [3] on this line courseTaken = a;
In my code, I never declared any pointer or char.
I don't quite understand what is going wrong here.
You can not assign array of strings string a[] to array courseTaken using = operator. The expression string a[] is equivalent to std::string*. That is why you get the compiler error.
This may be what you wanted:
#include <iostream>
using namespace std;
class Student
{
public:
string studentName;
string courseTaken[3];
void setStudent(string n, string a[]);
};
void setStudent(string n, string a[]);
void Student::setStudent(string n, string a[])
{
studentName = n;
for(int i=0; i < sizeof(courseTaken)/sizeof(courseTaken[0]); i++)
courseTaken[i] = a[i];
}
int main()
{
Student student;
string courses[3] = {"Cobol","C++","Fortran"};
student.setStudent("Eva", courses);
for (int i = 0; i < 3; i++){
cout << student.courseTaken[i] << endl;
}
return 0;
}
Output:
Cobol
C++
Fortran
It seems you don't understand array decay mechanism of C-format arrays.
For many context, an array name will be explained as a pointer to the first element of the array. And this pointer is a prvalue which just like this pointer, you can NOT assign to it.
the "modern Cpp way"(C++11) is to use std::array, which overloaded the =operator and stores the size of the array so that it won't be decayed while passing to a function.
The second way is to pass the reference, with a template you can ensure the array's size, then use std::memcpy. And you can add a parameter stores the array's size, and then you can use memcpy too.
I hope you use the first way, don't forget -std=c++11
This is because you are passing an array to a variable that's why this error occurs. To solve this problem you may use pointer in argument to solve this problem. Change your function to this.
void Student::setStudent(string n, string* a)
{
studentName= n;
courseTaken = a;
}

Returning arrays from a function in c++

I am trying to return an array from a function:
#include <iostream>
using namespace std;
int* uni(int *a,int *b)
{
int c[10];
int i=0;
while(a[i]!=-1)
{
c[i]=a[i];
i++;
}
for(;i<10;i++)
c[i]=b[i-5];
return c;
}
int main()
{
int a[10]={1,3,3,8,4,-1,-1,-1,-1,-1};
int b[5]={1,3,4,3,0};
int *c=uni(a,b);
for(int i=0;i<10;i++)
cout<<c[i]<<" ";
cout<<"\n";
return 0;
}
I pass two arrays from my main() into my uni() function. There I create a new array c[10] which I return to my main().
In my uni() function I try to merge the non-negative numbers in the two arrays a and b.
But I get something like this as my output.
1 -1078199700 134514080 -1078199656 -1216637148 134519488 134519297 134519488 8 -1078199700
Whereas when I try to print the values of c[10] in the uni() function it prints the correct values. Why does this happen??
Is this something related to the stack?? Because I have tried searching about this error of mine, and I found a few places on stackoverflow, where it says that do not allocate on stack but I couldn't understand it.
Further it would become very easy if I allocate my array globally, but if this is the case then everything shall be declared globally?? Why are we even worried about passing pointers from functions?? (I have a chapter in my book for passing pointers)
Admittedly, the std::vector or std::array approach would be the way to go.
However, just to round things out (and if this is a school project, where the teacher gives you the obligatory "you can't use STL"), the other alternative that will avoid pointer usage is to wrap the array inside a struct and return the instance of the struct.
#include <iostream>
using namespace std;
struct myArray
{
int array[10];
};
myArray uni(int *a,int *b)
{
myArray c;
int i=0;
while(a[i]!=-1)
{
c.array[i]=a[i];
i++;
}
for(;i<10;i++)
c.array[i]=b[i-5];
return c;
}
int main()
{
int a[10]={1,3,3,8,4,-1,-1,-1,-1,-1};
int b[5]={1,3,4,3,0};
myArray c = uni(a,b);
for(int i=0;i<10;i++)
cout << c.array[i] << " ";
cout << "\n";
return 0;
}
Note that the struct is returned by value, and this return value is assigned in main.
You have the value semantics of returning an instance, plus the struct will get copied, including the array that is internal within it.
Live Example
You're returning a pointer to a local object. In the uni function, the variable c is allocated on the stack. At the end of that function, all of that memory is released and in your for loop you are getting undefined results.
As suggested in the comments, std::array or std::vector will give you copy constructors that will allow you to return the object by value as you're trying to do. Otherwise you'll have to resort to something like passing your output array in as an argument.
You are returning a pointer to an array that is being deallocated at the return statement. It's a dangling pointer. It's UB.
Use an std::vector or std::array and return by value. There are compiler optimizations that will avoid inefficiencies.

Pointers and recurency - I'm trying to save memory

I'm trying to write program that create squere for string. Squere has to be larger then string.length(). If there is word 'C++' I need 2x2 array to fill it inside.
So I have written code
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
int pole(int &a,const int* l);
int main(){
string code;
cin >> code;
int wall=1;
pole(wall,code.length());
cout << wall;
system("PAUSE");
return 0;
}
int pole(int &a,const int* l){
if (a*a > l) return a;
else {
a+=1;
pole(a,l);
}
}
I bet that using pointer with recunrency save a lot of memory but I can't compile it. I'm trying to understand compilers error but is 2 hard for me ;/
Here is compiler list of errors
> in main()
11 25 Error] invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int (*)(int&, const int*)'
6 5> [Error] in passing argument 1 of 'int pole(int&, const int*)'
in pole() 17 12
>[Error] ISO C++ forbids comparison between pointer and
> integer [-fpermissive]
Here:
pole(pole, code.length());
You are passing as the second variable the result of length(), which is of type std::string::size_type, which the function pole accepts a pointer to int. Those two types are incompatible.
The second problem is that one branch of your if statement inside pole does not contain a return statement, thus giving your program Undefined Behavior.
You may want to change your function pole this way:
int pole(int &a, std::string::size_type l) {
// ^^^^^^^^^^^^^^^^^^^^^^
// Also, passing by reference is unnecessary here
if (a*a > static_cast<int>(l)) return a;
// ^^^^^^^^^^^^^^^^
// Just to communicate that you are aware of the
// signed-to-unsigned comparison here
else {
a+=1;
return pole(a,l);
// ^^^^^^
// Do not forget this, or your program will have Undefined Behavior!
}
}
Here you can see your modified program compile and run.
You are trying to use an unsigned integer (coming from std::string::length) as a pointer in:
pole(wall,code.length());
Change your pole declarations to:
int pole(int a, int l);
Saving memory on int is just nonsense there. Pointers are sometimes even more memory expensive than simple integers.
You should learn to save memory with huge objects instead.
int pole(int &a,const int* l){
if (a*a > l) return a;
else {
a+=1;
pole(a,l);
}
}
first, you cannot initialize int* l with size_t argument.
Also you do later comparison between address, not value pointed too.
Is this what you wanted?

C++, error invalid conversion from `int*' to `int'

I have the following C++ code:
#include <iostream>
using namespace std;
int main(){
}
int findH(int positionH[]){
return positionH; //error happens here.
}
The compiler throws an error:
invalid conversion from `int*' to `int'
What does this error mean?
positionH[] is an array, and its return type is int.
The compiler will not let you do that. Either make the parameter an int:
int findH(int positionH){
return positionH;
}
Or make the return type a pointer to an int:
int* findH(int positionH[]){
return positionH;
}
Or convert the array to an integer before return:
int findH(int positionH[]){
return positionH[0];
}
This line is invalid C++ (and invalid C too, which your code appears to be written in):
int bla[2] = findH(field, positionH);
bla is an array of 2 elements and cannot be initialised that way. findH returns int.
This error is coming while you are trying to do:
int *p =10;
that means you are assigning int value to pointertoint *p .
But pointer is storing address that means *p is taking 10 as address.
So
just do:
int i=10;
int *p=&i;
or
p=&i;
it will not give any error.
The error was caused because you returned a pointer and the compiler is expecting a int.
There is a very BIG difference between int * and int.
Also why are you returning positionH, arrays are passed by reference, there is no need to return it.
Better code would be
void option1(char** field, int[])
{
int findH(char **, int[]);
int positionH[2];
findH(field, positionH);
//positionH passed by reference, no need to return it
}
void findH(char **field, int positionH[])
{
for(int n = 0;n < 14 ; n++)
{
for(int m = 0; m < 14; m++)
{
if(field[m][n] == 'H')
{
positionH[0] = n;
positionH[1] = m;
}
}
}
}