I have the following code:
#include<iostream>
#include <string.h>
using namespace std;
int main(){
char str[100], str1[100];
cin>>str>>str1;
char c[strlen(str1)], flag[strlen(str1)];
int i, j, k = 0;
for (i = 0; i < strlen(str1); i++) {
flag[i] = 0;
}
for (i = 0; i < strlen(str); i++) {
for (j = 0; j < strlen(str1); j++) {
if (str[i] == str1[j] && flag[j] == 0) {
c[k] = str[i];
k++;
flag[j] = 1;
break;
}
}
}
if (k != 0)
cout<<c;
return 0;
}
It gives the correct output(first line is the input):
hello world
lo
But it requires to be put inside a function func()
when I put the code in a function, such as this -
#include<iostream>
#include <string.h>
using namespace std;
char * func(char * str, char * str1){
char c[strlen(str1)], flag[strlen(str1)];
int i, j, k = 0;
for (i = 0; i < strlen(str1); i++) {
flag[i] = 0;
}
for (i = 0; i < strlen(str); i++) {
for (j = 0; j < strlen(str1); j++) {
if (str[i] == str1[j] && flag[j] == 0) {
c[k] = str[i];
k++;
flag[j] = 1;
break;
}
}
}
if (k != 0)
return c;
return NULL;
}
int main(){
char str[100], str1[100];
cin>>str>>str1;
cout<<func(str,str1);
return 0;
}
The output comes like
hello world
Note that the second output line contains an ASCII character What is the mistake in here? Can't I return a string array like this?