what's the meaning of the function parameter declaration? - c++

I have see this in the http://en.cppreference.com/w/cpp/language/function
int f(int a, int *p, int (*(*x)(double))[3]);
what's the meaning of int (*(*x)(double))[3]?

(*x) ensure x is a pointer then (*x)(double) will give us a function pointer whose parameter is a double and the next is (*(*x)(double)) which means the function will return a pointer p and p is depicted by int int (*p)[3] which in the end gives us a pointer pointing to an array of int[3]
So all in all, what we have here is a pointer pointing to a function whose single parameter is a double and the function returns a pointer pointing to an array of int[3].
Here is a simple example to demonstrate it, hope it can be helpful.
#include <iostream>
using namespace std;
typedef int int3[3];
int arr3[3]{1, 2, 3};
int3 * get3Int(double x){
int (*arr)[3] = &arr3;
return arr;
}
int testFunctionPointer(int (*(*x)(double))[3]){
int (*arr)[3] = x(1.0);
for(auto n: *arr)
cout<<n<<endl;
return 0;
}
int main(){
testFunctionPointer(get3Int);
return 0;
}

Related

c++ error "Braces around scalar initializer for type int*"

Error: braces around scalar initializer for type int*
I'm trying to pass an array to the function but I keep getting this error in the initialization step.
How can I fix this?
#include <iostream>
using namespace std;
void func (int *p[4]);
int main()
{
int *p[4]={ {1,4,5},{3,5,6},{6,6,2},{6,5,3}}; //The error appears here
func(p);
return 0;
}
void func (int *p[4])
{
for(int i=0;i<4;i++)
{
for(int j=0;j<1;j++)
{ cout<<p[i][j]; }
}
cout<<" \t";
}
Problem is what is p.
Whit this definition:
int *p[4];
this is 4 element array of pointers to int.
I guessing you wanted this:
int (*p)[3];
pointer to 3 element array of ints.
Also to use initialization you need an array.
Here is working example.
The variable p is an array of pointers. { 1, 4, 5 } is not a pointer.
You need to make p an array of arrays:
int p[4][3] = { ... };
Because of that change, you have to change the func function argument as well, as p will now decay to a pointer to an array, of type int (*)[3] (that is, the argument for func should be int (*p)[3]).
This would work, however you are going to lose array information because they will decay into pointers:
int arr1[] = { 1,4,5 };
int arr2[] = { 3,5,6 };
int arr3[] = { 6,6,2 };
int arr4[] = { 6,5,3 };
int *p[4] = { arr1, arr2, arr3, arr4 };

Pointing to an element of an array

Below is the cluttered version of my code that shows only the basic structure.
I'm just trying to use a pointer to an element of an array in a function but
I constantly get
C:\Users\whale\Desktop\20_Pay2.cpp:4:45: error: expected ',' or '...' before 'money'
but I still have no clue what I'm missing. Any help is appreciated!
#include<stdio.h>
#include<stdlib.h>
void pay_amount (int *dollars, int k, int *money[k]);
int main(void)
{
int dollars=180, i=1, a[4]={20,10,5,1};
pay_amount (&dollars, i, &a[i] );
return 0;
}
void pay_amount (int *dollars, int k, int *money[k])
{
printf("functions");
}
The problem is that the parameter list you're using (int k, int *money[k]) is not valid C++ syntax. Unfortunately g++ produces a less than helpful message for this.
The good news is that you don't want this anyway: It would declare money to be an array of k pointers to int. What you actually want is just a pointer to int:
void pay_amount(int *dollars, int k, int *money);
a is an array of int, a[i] is a single int, so &a[i] is a pointer to an int, int *.
Here :
pay_amount (&dollars, i, &a[i] );
The third parameter you pass is a pointer to a integer.
But in your function declaration, you have that :
void pay_amount (int *dollars, int k, int *money[k]);
int *money[k] as a function parameter does not seems correct.
You may want to do that :
void pay_amount (int *dollars, int k, int *money);
Here, money is a pointer to an integer

C++ n00b learning pointers, trying to return a pointer to an array [duplicate]

This question already has answers here:
How to access a local variable from a different function using pointers?
(10 answers)
Closed 5 years ago.
Could anybody please explain what's wrong with this C++ code?
I can see that you cannot return an array in C++ (like in other languages) so I'm returning a pointer. I learned that there's no point in setting the pointer to the address of "myArray" - because "myArray" is already an address (first item)
the output I expected was 1,2,3,4
on different (online) compilers I'm getting different weird results here, including:
1, 4, -993994160, 32767
1, -1077229596, -1077229588, 1075514957
1,2,3,3 (so close)
so here's my dodgy code:
#include <iostream>
using namespace std;
int* getArray(){
int myArray[] = {1,2,3,4};
int* pointerToArray = myArray;
return pointerToArray;
}
void printArray(int inputArr[], int length) {
for (int i = 0; i < length; i++) {
cout << inputArr[i] << ", ";
}
}
int main()
{
printArray(getArray(),4);
return 0;
}
any help you could provide is VERY much appreciated!
You're returning a pointer to a function's local variable, which ceases to exist when the function returns.
int* getArray(){
int myArray[] = {1,2,3,4};
int* pointerToArray = myArray;
return pointerToArray;
}
myArray effectively disappears when getArray() returns.
This will work as it gives the variable static duration, which means it exists all the time (but then there's only one instance of the variable instead of an instance for each invocation of the function):
int* getArray(){
static int myArray[] = {1,2,3,4};
int* pointerToArray = myArray;
return pointerToArray;
}
There are a multitude of other solutions, including creating an array dynamically using new.
with std::array, you may do:
#include <iostream>
#include <array>
std::array<int, 4> getArray(){
return {{1,2,3,4}};
}
template <std::size_t N>
void printArray(const std::array<int, N>& a) {
for (int e : a) {
std::cout << e << ", ";
}
}
int main()
{
printArray(getArray());
}
You've got a scoping problem, for one. myArray is declared statically in getArray, so as soon as getArray returns, its memory is free for others to use/overwrite.
If you want to use a C array:
#include <alloc.h>
...
int *getArray()
{
int *myArray = (int *)malloc(4 * sizeof(int));
myArray[0] = 1;
...
myArray[3] = 4;
return myArray;
}
int printArray(int *array, uint length) {
...
free(array);
}
Filling in the ellipses appropriately, of course.

c++ in function- an error for "a reference .. can not be initialized with a value"

I 'm still confused for my problem after spending an amount of time to digging related posts/online resources.
My sample codes (test.cc) are :
void testsub(const int* &xx );
int main ()
{
int* xx;
xx= new int [10];
testsub(xx);
}
void testsub(const int* & xx){}
The compiling error message(pgcpp) read
"test.cc", line 7: error: a reference of type "const int *&" (not const-qualified)
cannot be initialized with a value of type "int *"
testsub(xx);
^
1 error detected in the compilation of "test.cc"."
Why? Your help is appreciated.
Best wishes,
Ting
int* cannot be used where the argument type is const int* &.
Say you have:
const int a = 10;
void foo(const int* & ip)
{
ip = &a;
}
int main()
{
int* ip = NULL;
foo(ip);
*ip = 20; // If this were allowed, you will be able to
// indirectly modify the value of "a", which
// is not good.
}
As the error message says, the argument type is incompatible; the function wants a pointer to const int, while you supply a pointer to int.
If you're asking why that's incompatible: allowing it would allow you to break const-correctness, as in this example:
void testsub(const int* &xx ) {
static const int x;
xx = &x;
}
int* xx;
testsub(xx); // Shouldn't be allowed, because...
*xx = 666; // BOOM! modifying a constant object.
Maybe try this
void testsub(const int* xx );
int main ()
{
int xx [10];
testsub(xx);
}
void testsub(const int* xx){}
You don't need the &, because you are passing a pointer as argument.
When you forward a "C-Array" (your int[10]), you will have a pointer to the first element of this array in your function.
void testsub(const int* xx );
int main ()
{
int* xx;
xx= new int [10];
testsub(xx);
}
void testsub(const int* xx){}
I think you got confused by your book, because they always write something like "Call by reference". That doesn't mean to pass the parameter as a reference with the &.
Often it is useful to pass also the size of the array to the function ... so it would like:
void testsub(const int* xx, size_t arraySize);
int main ()
{
int* xx;
xx= new int [10];
testsub(xx, 10);
}
void testsub(const int* xx, size_t arraySize){}
Now you can access the array in your function and you have the possibility to check the index, if you want to access the array with an index.
void testsub(int* xx, size_t arraySize)
{
for(size_t i=0; i<arraySize; ++i)
// ^ this way you will never try to access
// memory, which does not belong to the array
// => no seg fault, or whatever happens
{
// do sth. with the array ... for example setting values to 0
xx[i] = 0;
}
}

C++ passing an array pointer as a function argument

I'm trying to use pointers of arrays to use as arguments for a function which generates an array.
void generateArray(int *a[], int *si){
srand(time(0));
for (int j=0;j<*si;j++)
*a[j]=(0+rand()%9);
} //end generateArray;
int main() {
const int size=5;
int a[size];
generateArray(&a, &size);
return 0;
} //end main
But when I compile this this message appears:
cannot convert `int (*)[5]' to `int**' for argument `1' to `void generateArray(int**, int*)'
You're over-complicating it - it just needs to be:
void generateArray(int *a, int si)
{
for (int j = 0; j < si; j++)
a[j] = rand() % 9;
}
int main()
{
const int size=5;
int a[size];
generateArray(a, size);
return 0;
}
When you pass an array as a parameter to a function it decays to a pointer to the first element of the array. So there is normally never a need to pass a pointer to an array.
int *a[], when used as a function parameter (but not in normal declarations), is a pointer to a pointer, not a pointer to an array (in normal declarations, it is an array of pointers). A pointer to an array looks like this:
int (*aptr)[N]
Where N is a particular positive integer (not a variable).
If you make your function a template, you can do it and you don't even need to pass the size of the array (because it is automatically deduced):
template<size_t SZ>
void generateArray(int (*aptr)[SZ])
{
for (size_t i=0; i<SZ; ++i)
(*aptr)[i] = rand() % 9;
}
int main()
{
int a[5];
generateArray(&a);
}
You could also take a reference:
template<size_t SZ>
void generateArray(int (&arr)[SZ])
{
for (size_t i=0; i<SZ; ++i)
arr[i] = rand() % 9;
}
int main()
{
int a[5];
generateArray(a);
}
You do not need to take a pointer to the array in order to pass it to an array-generating function, because arrays already decay to pointers when you pass them to functions. Simply make the parameter int a[], and use it as a regular array inside the function, the changes will be made to the array that you have passed in.
void generateArray(int a[], int si) {
srand(time(0));
for (int j=0;j<*si;j++)
a[j]=(0+rand()%9);
}
int main(){
const int size=5;
int a[size];
generateArray(a, size);
return 0;
}
As a side note, you do not need to pass the size by pointer, because you are not changing it inside the function. Moreover, it is not a good idea to pass a pointer to constant to a parameter that expects a pointer to non-constant.
I'm guessing this will help.
When passed as functions arguments, arrays act the same way as pointers. So you don't need to reference them. Simply type:
int x[]
or
int x[a]
. Both ways will work. I guess its the same thing Konrad Rudolf was saying, figured as much.
This is another method . Passing array as a pointer to the function
void generateArray(int *array, int size) {
srand(time(0));
for (int j=0;j<size;j++)
array[j]=(0+rand()%9);
}
int main(){
const int size=5;
int a[size];
generateArray(a, size);
return 0;
}