Error in program with structures and pointers (Structures, C++) - c++

I have a structure , which contains three variables under the object list.-Names, registration nos, amount.
struct vendor
{
int reg, amt;
char add[30];
}list[10];
I have made a function to find the minimum amount(amt) ,using the referencing concept.
int low(vendor *p, int n)
{
int i;
min = (p->amt);
for(i =1;i<n;i++)
{
if(min > *(p->amt))
{
min = *(p->amt);
}
p++;
}
return min;
}
In the main I have included the syntax:
low(list, n);
I am getting an error:
Invalid argument of unary '*' operator.
I have tried using the dot operator also and is not working.
This is my first program in pointers in structs with functions.
Can you please point out the error in the code.
Thank You very much
Anupam
(Update) the full code:
#include <iostream>
using namespace std;
struct vendor
{
int reg, amt;
char add[30];
}list[10];
int low(vendor *p, int n)
{
int i;
min = (p->amt);
for(i =1;i<n;i++)
{
if(min > (p->amt))
{
min = (p->amt);
}
p++;
}
return min;
}
int main()
{
int i;
int fa;
int n,fr;
cin >> n;
for(i =0;i<n;i++)
{
cin >>list[i].reg>>list[i].add>>list[i].amt;
// Enter reg no. , address and amount.
}
low(list, n); // Calling function
for(i = 0;i<n;i++)
{
if(fr == list[i].amt)
// This is to check for position of least amount.
// For printing the reg no. and address of least amt.
{
fa = i;
}
}
cout << fr <<"\n" << fa <<endl;
// print the reg no. and address of least amt.
}
Errors:
Overloaded function with no contextual type information.
Invalid operands of types <unresolved overloaded function
Cannot resolve overloaded function

The declaration for min is missing in low() function.
int min = (p->amt);
This should help you compile your code.

p is a pointer to a vendor. *p is a vender. p->amt is an int.
So when you want the amt of an object that is pointed to by p you can do it in one of two ways: p->amt or (*p).amt
You fix your code by using p->amt or (*p).amt. *p->amt or *(p->amt) are invalid.

p is a object of vendor which type is pointer . "->" is used to use pointer object . So use p->amt .
you can also use (*p).amt .
Updated Answer :
decleration of min is missing . please use this :
int min = p->amt ;
or use this :
int min = (*p).amt;

Related

Confusion about pointer to an array as a function parameter

In my textbook about c++ I have the following code example:
using std::cout;
using std::endl;
int main() {
int aArr[4] = { 3,4,2,3 };
int bArr[3] = { 2,3,1 };
cout << "Append: " << endl;
printArray(aArr, 4); cout << " + "; printArray(bArr, 3);
int* cArr = append(&aArr, bArr);
cout << " = "; printArray(cArr, 7); cout << endl;
return 0;
}
Does the "&" symbol in front of "aArr" in the call to append in main mean that the address of aArr is passed, or that a reference to aArr is passed.
The question then asks for me to implement a function append which takes two arrays: the first array (in the first argument) of size 4 by array pointer and the second array (in the second argument) of size 3 by reference and returns a pointer to an array of size 7. I have declared that function as (in the appropriate header file)
int* append( int foo[4], int (&secondArray) [3] );
Has the author perhaps misplaced the order of the "&" symbol in the append method (that it should be in front of "bArr")?
The compiler can help you out in cases like this.
Lets assume that this is the function prototype for your append function:
int* append( int foo[4], int (&secondArray) [3]);
I can test this out with this simple bit of code:
int* append( int foo[4], int (&secondArray) [3])
{
return 0;
}
int main() {
int aArr[4] = { 3,4,2,3 };
int bArr[3] = { 2,3,1 };
int* cArr = append(&aArr, bArr);
return 0;
}
But the compiler doesn't like this, failing with this error:
test.cpp(9): error C2664: 'int *append(int [],int (&)[3])':
cannot convert argument 1 from 'int (*)[4]' to 'int []'
As you can see it doesn't like the &aArr argument 1 at line 9 as it does not match the argument 1 defined by the function at line 1. From the error message it is even nice enough to give a reason why it thinks they don't line up.
Now using the hint from the compiler it is clear the function should in fact look like this:
int *append(int (*foo)[4], int secondArray[3])
{
return 0;
}
int main() {
int aArr[4] = { 3,4,2,3 };
int bArr[3] = { 2,3,1 };
int* cArr = append(&aArr, bArr);
return 0;
}
With that change the compiler is happy to accept the code as correct.
Now comparing the two you can see the difference is in the first case the first argument was passed as an array of 4 integers, whereas in the second case it is passed as the address of an array of four integers.
Just from the english you can tell these are two very different things.
EDIT: Here is an extension of that example that shows how to access the data inside the function.
#include <stdio.h>
int *append(int (*foo)[4], int secondArray[3] )
{
int *foo1 = *foo;
for (int i = 0; i < 4; ++i)
{
printf("foo: %d\n", foo1[i]);
}
for (int j = 0; j < 3; ++j)
{
printf("secondArray: %d\n", secondArray[j]);
}
return 0;
}
int main() {
int aArr[4] = { 3,4,2,3 };
int bArr[3] = { 12,13,11 };
int* cArr = append(&aArr, bArr);
return 0;
}
Compiling an running this code produces this output:
foo: 3
foo: 4
foo: 2
foo: 3
secondArray: 12
secondArray: 13
secondArray: 11

Class accept and return array

I try to create a class that accept and return an array but I got some problem. I'm not sure if it is legal to return an array from a class. Or it could be done by returning an pointer to the array. Thank for any solution to the problem.
#include <iostream>
using namespace std;
class myclass {
private:
int Array[10];
public:
myclass (int temp[10]) {
for (int i = 0; i < 10; i++) {
Array [i] = temp [i];
}
}
int returnArray () {
return Array; // error here, I'm not sure if it is legal to return an array.
}
int* returnArray2 () {
return this->Array; // hope it will return a pointer to the array
}
};
int main () {
int Array[10] = {1,2,3,4,5,6,7,8,9};
myclass A(Array);
cout << A.returnArray() << endl; // try to return an array and print it.
myclass* ptr = &A;
cout << *ptr->returnArray2 << endl; // error here
return 0;
}
First of all it is better to write the constructor either like
myclass ( const int ( &temp )[10] ) {
for (size_t i = 0; i < 10; i++) {
Array [i] = temp [i];
}
}
or like
myclass ( int temp[], size_t n ) : Array {} {
if ( n > 10 ) n = 10;
for (size_t i = 0; i < n; i++) {
Array [i] = temp [i];
}
}
Or even you may define the both constructors.
As for the returning value then you may not return an array. You may return either a reference to an array or a pointer to the entire array or a pointer to its first element
For example
int ( &returnArray () )[10] {
return Array;
}
In this case you can write in main
for ( int x : A.returnArray() ) std::cout << x << ' ';
std::cout << std::endl;
As for this statement
cout << *ptr->returnArray2 << endl; // error here
then you forgot to place parentheses after returnArray2. Write
cout << *ptr->returnArray2() << endl;
And the following member function is wrong because the expression in the return statement has type int * while the return type of the function is int
int returnArray () {
return Array; // error here, I'm not sure if it is legal to return an array.
}
So either the function will coincide with the the second member function if you specify its return type like int *. Or you could change the return expression to *Array
int returnArray () {
return Array; // error here, I'm not sure if it is legal to return an array.
}
This is illegal because Array is not of int type. Your returnArray2 is valid, however. As for this line:
cout << *ptr->returnArray2 << endl; // error here
This is illegal because returnArray2 is a function; you must call it to return the int*:
cout << *ptr->returnArray2() << endl; // prints the first value in the array
Other notes:
Your capitalization is backwards; you should call your class MyClass and your member array arr or arr_, or you will confuse a lot of people.
return this->Array; this is redundant, you can simply return Array;
If you haven't heard of std::vector and std::array you should research those, as they are generally superior to C-style arrays.
In general, I would suggest to read a c++ book to get your basics correct as there are lot of issues in the code you posted.
Regarding your main question about exposing C style arrays in class public API, this is not a very robust mechanism. Do it if it is absolutely essential because of existing code but if possible prefer to use std::vector. You will mostly always end up with better code.
Other answers have corrected your coding errors, so i won't repeat that.
One other thing, your code suggests that the array size is fixed. You can pass and return the array by reference as well. Refer to: General rules of passing/returning reference of array (not pointer) to/from a function?

How to pass in an array of objects: error c2146: syntax error : missing ')' before identifier 'myMembers'

I'm a c++ student and this is my first post here.
I have an array containing Member objects (which will be dynamic in the future). I'm trying to pass the array into a function, getLogin in my case.
I think I have some of the syntax wrong, I'm still struggling to understand dynamic arrays and correct syntax for pointers in different situations. Visual Studio is showing an error with myMembers, where it is written as a parameter for getLogin.
#include <iostream>
#include <string>
#include "Member.h"
using namespace std;
int getLogin( const int, Member[] );
int main(){
int numAccounts = 0;
int accCapacity = 5;
int currentAcc = 0;
Member member[5];
currentAcc = getLogin( numAccounts, member );
return 0;
}
int getLogin( const int lastAcc, Member[] myMember ){
int accNum;
cout << "account number:" << endl;
cin >> accNum;
if( accNum > 0 && accNum <= lastAcc ){
myMember[accNum].setLoggedIn( true );
}
else{
accNum = 0;
}
return accNum;
}
(p.s. What I really want is a pointer to the array, because I don't want a copy of the entire array to be created. However, I believe that using the array name is actually like using a pointer to the first element. So I think I don't need to worry about that.)
Change the definition of getLogin() as follows:
int getLogin( const int lastAcc, Member myMembers[] ){
//...
}
(And of course you should better use std::vector or std::array, but since this is a homework, this advice probably makes no sense)
If you want to pass an array of pointers then you have to change
the implementation of your function getLogin:
int getLogin( int lastAcc, Member** myMembers )
{
int accNum;
if( accNum > 0 && accNum <= lastAcc )
{
myMembers[accNum]->setLoggedIn( true );
}
else{
accNum = 0;
}
return accNum;
}
and this is how you pass an array to it:
int numAccounts = 0;
int accCapacity = 5;
int currentAcc = 0;
Member* members[numAccounts];
for ( int i =0; i < numAccounts; i++)
{
members[i] = new Member();
}
currentAcc = getLogin( numAccounts, members )

Initializing chained hash table to NULL. Get "lvalue required as left operand of assignment" error. Why? Here is my code:

I am trying to create a chained hash table. I have started by building a dynamic array and am now trying to initialize each array pointer to NULL. But I get the error "lvalue required as left operand of assignment". Why? Here is my code:
#include <iostream> // for i/o functions
using namespace std;
const int HTSIZE = 997; //size of the hash table
struct CHTNode
{
int value;
CHTNode *next;
};
void InitializeTable(CHTNode* &cHT);
int main()
{
CHTNode *chainedHT;
chainedHT = new(nothrow) CHTNode[HTSIZE];
if (chainedHT == NULL)
{
cout << "ERROR: Memory allocation error"
<< endl;
return 1;
} //end if
else
{
InitializeTable(chainedHT);
}
}
void InitializeTable(CHTNode* &cHT)
{
for (int i = 0; i < HTSIZE; i++)
&cHT[i] = NULL; //ERROR FOR THIS LINE
}
The address-of operator & returns the address of the given expression, so &cHT[i] evaluates to the address of the ith element of cHT. It seems you're trying to assign to the variable cHT[i], but what you're doing right now is trying to assign to the address value of cHT[i], which makes no more sense than trying to assign to a constant.
You do not have an array of pointers. You allocated an array of objects of type CHTNode.
You could value initialize this array when it was allocated. For example
chainedHT = new(nothrow) CHTNode[HTSIZE] {};
If you want to write a separate function that zero-injitialize each element of the array then the function could be declared like
void InitializeTable( CHTNode* cHT, int n );
and defined like
void InitializeTable( CHTNode* cHT, int n )
{
for ( int i = 0; i < n; i++ ) cHT[i] = {};
}
As for erroneous statement
&cHT[i] = NULL;
then it does not make a sense. Expression &cHT[i] is a temporary object that you are try to assign.

Run time error for dynamic memory allocation in C++

I am a newbie for OOP concepts and while trying to solve Project Euler Problem 7, to find 10001th prime number, I tried to do it using a class but encountered 2 major errors.
instantiating the class prime_n
initializing its argument
I have posted the code here for reference:
#include<iostream>
#include<cstdio>
using namespace std;
class prime_n
{
int j,k;
int n;
int *store;
public:
prime_n(int num)
{
n=num;
store[n];
}
static int isPrime(int j)
{
for(int i=2;i*i<=j;i++)
{
if(j%i==0) return 0;
}
return 1;
}
void find_n()
{
for(int i=0;i<n;i++)
{
store[i]=0;
}
store[0]=2;
j=3;
k=1;
while(store[n-1]==0)
{
if(isPrime(j)) store[k++]=j;
j+=2;
}
}
int get_num()
{
int value=store[n-1];
return value;
}
};
int main()
{
int num, req_num;
printf("Enter the position at which prime number is to be found ");
scanf("%d",&num);
printf("\nnumber = %d",num);
prime_n p = new prime_n(num);
req_num = p.get_num();
printf("The required prime number is %d\n",req_num);
return 0;
}
It would be a great help if someone could help me figure out where I am actually going wrong. Thanks a lot in advance!
Use
prime_n p(num);
or (not recommended in this particular case)
prime_n * p = new prime_n(num);
// some other code
req_num = p->get_num(); // note the -> operator replacing . in case of pointers
delete p;
The first case declares p on stack and it is automatically deallocated when the program leaves the scope (main function in this case)
The second one allocates space on heap and p is the pointer to it. You have to deallocate the memory manually.
As for your second question, the C++ way would be
#include <iostream>
...
int num;
std::cout << "Enter the position at which prime number is to be found "
std::cin >> num;
std::cout << std::endl << "Number = " << num << std::endl;
You provide a constructor:
prime_n(int num)
{
n=num;
store[n];
}
I think you are under the impression that store[n] creates an array with n elements, but that is not so; it attempts to access the (n+1)th element of an an array. Since store does not point anywhere (we are in the constructor, after all), the program crashes.
You probably want to write store = new int[num] instead.
And then I cannot see any call to find_n() originating from get_num() which is called in main(), so that your program would for now just return a random value.