0

I made some code in C with two functions.

One functions looks for a word (group of characters) and then saves it to a string. The other function shows what's inside the string. I can't find the right way to save the returning value to a string.

Here is my code:

#include <stdio.h>

char SchrijfString(void);
void LeesString(char);

int main(void)
{
    char x[60];
    x = SchrijfString(x);
    LeesString(x);
    return 0;
}

char SchrijfString(char x[])
{
    printf("geef een string in: \n");
    gets(x);
    return x;
}

void LeesString(char x[])
{
    printf("In de string zit:\n %s", x);
    getchar();
}
savram
  • 500
  • 4
  • 18
reyntjensm
  • 27
  • 9
  • 3
  • `x = SchrijfString(x);` Since `x` itself has been updated, there is no need to write back. --> `SchrijfString(x);`, `char SchrijfString(char x[])` --> `char *SchrijfString(char x[])` – BLUEPIXY Oct 25 '17 at 16:02
  • In `char x[60]; x = SchrijfString(x);` you can't do that: you already defined that `x` is an array. Use a pointer type as the last comment. – Weather Vane Oct 25 '17 at 16:04
  • The `return` in `SchrijfString()` returns the wrong type; it returns a `char *`, but the function signature says it returns a single `char`. In context, there's not much virtue in returning the `char *` since it is simply the value you passed into the function. You don't even return NULL if `gets()` -- which you shouldn't be using anyway -- indicates EOF. – Jonathan Leffler Oct 25 '17 at 16:06
  • I would encourage your to hand over the "code" to a C compiler. When it the compiler stops complaining please improve the question. – harper Oct 25 '17 at 16:51

1 Answers1

0

The gets function is already populating x with a string specified by the user, so no need to return anything from SchrijfString or to assign anything to x back in main. Your function prototypes don't match the definitions. They need to be the same.

Also, gets is deprecated because it is unsafe. Use fgets instead.

void SchrijfString(char x[], int len);
void  LeesString(char x[]);

int main(void)
{
    char x[60];
    SchrijfString(x, sizeof(x));
    LeesString(x);
    return 0;
}

void SchrijfString(char x[], int len)
{
    printf("geef een string in: \n");
    fgets(x, len, stdin);
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
dbush
  • 205,898
  • 23
  • 218
  • 273
  • See [Why `gets()` is so dangerous it should never be used](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) – Jonathan Leffler Oct 25 '17 at 16:14
  • `fgets` is not just a drop-in replacement for `gets`. It's safer, but unlike `gets` it leaves the trailing `'\n'` in the target array. – Keith Thompson Oct 25 '17 at 16:36