Please guide me on this code, I want to store list of 5 data using array and function, this is a piece of code of mine, but this is giving me an error ("33"):
Cannot convert `ABC (*)[5]' to `ABC*' for argument `1' to `void pass(ABC*)'
Code:
#include <iostream>
using namespace std;
struct ABC{
char name[20];
int phone;
char address[20];
};
void pass(ABC *abc){
for(int i=0; i<5;i++){
cout<<"Enter name"<<endl;
cin>>abc[i].name;
cout<<"Enter phone"<<endl;
cin>>abc[i].phone;
cout<<"Enter address"<<endl;
cin>>abc[i].address;
}
}
int main()
{
ABC abc[5];
pass(&abc);
system("PAUSE");
return EXIT_SUCCESS;
}
You can use pass(&abc[0]); or pass(abc); to get a pointer to the first element in the array. Otherwise if you use &abc alone you get a pointer to a whole array[5] not the elements inside the array.
Arrays are not pointers. But they can decay to pointers when you are doing function calls.
So you can pass your array like this:
pass(abc);
Related
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;
}
I was trying to make a function for finding number of elements in an array. For this I approached for following code:
#include<iostream>
#include<stdlib>
int no_of_ele(A[]) //function to return size of array
{
return (sizeof(A)/sizeof(A[0]);
}
void main()
{
system("cls");
int arr[5] = {1,2,3,4,5};
cout<<"Number of elements in array are "<<no_of_ele(arr)<<endl;
system("pause");
}
In this approach I got output as follows:
Then, I did this:
cout<<"Size of array is "<<sizeof(arr)<<endl;
cout<<"Size of data type is "<<sizeof(arr[0]);
Now I got absolutely correct output of size as follows:
Why is it?
There are better ways these days, but the closest is:
#include<iostream>
template<std::size_t N>
int no_of_ele(int (&A)[N]){
return sizeof(A)/sizeof(A[0]); // or just return N
}
int main(int argc, char* argv[]){
int arr[5] = {1,2,3,4,5};
std::cout<<"Number of elements in array are "<<no_of_ele(arr)<<std::endl;
return 0;
}
Greetings to 1998. The question is, does Turbo C++ support templates?
See here for more: Is it possible to overload a function that can tell a fixed array from a pointer?
The array decayed to pointer when passed to your function.
sizeof(int)/sizeof(int)... = 1
Reason for this, the parameters are pushed on stack to the function. The compiler as declared by your function declaration will just send the address of your array.
When passing an array as a parameter
int func(int arr[])
Is just as:
int func(int *arr)
Giving an array as a function argument you can't determine its size using the sizeof.
I know even if i pass an array by typing arrayname as argument (ex: getArrayInput(arrayexample); ), it will copy only the adress value of first element not entire array,still i wonder why these code gives error. I know this not the way how it should implemented but i want to understand this error.
main.cpp|13|error: cannot convert 'int*' to 'int**' for argument '1' to 'void getArrayInput(int**)'|
#include <iostream>
using namespace std;
void getArrayInput(int * []);
int main()
{
cout<<"Enter scores on by one.." << endl;
cout<<"To terminate input enter -1"<<endl;
int listof[10]={};
int *ptScores =listof;
getArrayInput(ptScores);
return 0;
}
void getArrayInput(int * []){
for(int i=0;i<10;i++){
cin>>*(pt+i);
if(*(pt+i))=-1){
break;
}
else{
cout<<"Enter next.."<<endl;
}
}
}
It is because
int *
and
int[]
are both of type
int *
therefore, you are here asking for a
int **.
try replacing
void getArrayInput(int * []) by void getArrayInput(int *)
In C, arrays decay in to pointers. In some cases, they are interchangable.
ptScores is of type int* (pointer to int).
getArrayInput expects an int*[] (array of pointers to int).
int*[] decays in to int** (pointer to pointer to int).
The error says you're giving an int* (ptScores) to something that expects an int** (getArrayInput).
How do you fix this?
Take an int*.
void getArrayInput(int* pt){
for(int i=0;i<10;i++){
cin>>pt[i];
if(pt[i]=-1){
break;
}
else{
cout<<"Enter next.."<<endl;
}
}
}
I am trying to create a C++ program which stores many names linked to a numeric value, and can alter the numeric value when the name is entered. My question is: if I create an array in the main function, can it be accessed from another function? And if so, what should be done for that?
Attaching code (part of it)
#include <iostream>
#include <fstream> //required as input\output is from\to file
#include <string>
using namespace std;
int name_checker (string input);
int main()
{
int cases;
cin >> cases;
string names[cases]; //this is the array.
int i=0;
while (i<cases)
{
cin >> names[i];
i++;
}
}
int name_checker (string input);
{
//i want the data stored in above array to be availible here. possible?
}
Yes, possible. Pass the array as an argument to the function.
Change the function as -
int name_checker (string input[]);
And pass the array to the function -
name_checker(names);
Note: Changing the values in the function will also affect the original values.
You should consider using a class.
So you can make the array a field (as πάντα ῥεῖ suggested you should consider using a vector ) and name_check a member function.
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.