Reputation: 434
I'm trying to figure out how returning an array works out in C. This is the code. What I'm trying to do is save an array and then print it by using a function return. What am I doing wrong here?
#include <stdio.h>
#define DIM 50
char *func (char input[]);
int main(void)
{
char input[DIM];
printf("input? ");
fgets(input, DIM, stdin);
printf("output: %s", func(input));
return 0;
}
char *func(char input[])
{
int i;
char output[DIM];
for(i = 0; i < DIM; i++)
output[i] = input[i];
return &output;
}
Upvotes: 1
Views: 770
Reputation: 445
It is possible to return the adress, but not that way.
Try this
char *func(char input[])
{
int i;
char *output = (char*)malloc(sizeof(char) * DIM);
for(i = 0; i < DIM; i++)
output[i] = input[i];
return output;
}
An other way is to do it like 'Call by reference'. Looks like this
void func(char *input, char *output)
{
int i;
for(i = 0; i < DIM; i++)
output[i] = input[i];
}
And your main should look like this
int main()
{
char *input = (char*)malloc(sizeof(char) * DIM);
char *output = (char*)malloc(sizeof(char) * DIM);
printf("input? ");
fgets(input, DIM, stdin);
func(input, output);
printf("output: %s", output);
free(input);
free(output); // after you finished your work with this variable
return 0;
}
Upvotes: 1
Reputation: 158449
In func
you are returning a pointer to a local variable here:
return &output;
which will not exist once you leave the function and as Jonathan pointed out, you are actually returning a pointer to an array of char
, if you wanted to return the pointer you would have just done return output
but that would still be wrong.
If you can not use dynamic allocation then you would need to pass the output as an argument.
Upvotes: 1
Reputation: 753455
One problem is already stated by the other answers:
The other problem is that given:
char output[DIM];
the type of:
return &output;
is 'pointer to array of char
' and not char *
. If you wrote:
return output;
you would be OK — if you sorted out the duration of the returned value. Similarly, if you defined the function as returning a pointer to an array, you'd be alright:
char (*func(char input[]))[]
{
static char output[DIM];
...
return &output;
}
Note that using the static variable like that renders the function non-reentrant (unsafe for use in threaded applications) unless the array is in fact constant (in which case, the definitions should say it is constant).
Upvotes: 1