1

I am trying to return an array from a local function to the main function but every time it shows a compilation error of

invalid conversion from ‘int’ to ‘int*’ [-f permissive]

#include <bits/stdc++.h> using namespace std; int* GCDstrings(int a,int b,int *F) { int i; if(a%b==0) { F[0]=1; for(i=1;i<a;i++) F[i]=0; } return F; } int main() { int T; cin>>T; while(T--) { int x,y; cin>>x>>y; int f[x]; int* p; p=GCDstrings(x,y,f[x]); for(int i=0;i<=x;i++) cout<<*(p+i); } return 0; } 

What is the mistake I am doing here?

3
  • It doesn't make much sense to return the same array. Commented Jan 27, 2019 at 7:48
  • 1
    VLA is just a compiler extension and not supported by C++ standard. And why not use std::vector? Commented Jan 27, 2019 at 7:51
  • 1
    for(int i=0;i<=x;i++) will access the one past the end pointer... Commented Jan 27, 2019 at 8:01

1 Answer 1

3

You error lies in this part of your code

int f[x]; int* p; p=GCDstrings(x,y,f[x]); 

You are trying to create a dynamic array and then pass it to the function.

When you pass an array you should only pass the location to its first value.

You can either do

p=GCDstrings(x,y,f); 

during your function call.

Or you can go with,

p=GCDstrings(x,y,&f[0]); 

For more information, check out this link https://www.programiz.com/cpp-programming/passing-arrays-function.

Also you might want to look into dynamic memory allocation for future, however it looks like you are beginning so allocating an array of length x like this is okay, but do check that out later. https://www.geeksforgeeks.org/new-and-delete-operators-in-cpp-for-dynamic-memory/

If any more problems, comment and we will see,

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.