I am having trouble with a function that should read a string from the user. I am always getting (null) as the output.
Is this even a "right" approach for that kind of problem?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int getString(char *input);
int main(void)
{
char *arr = NULL;
printf("please enter string: ");
getString(arr);
printf("%s", arr);
return 0;
}
int getString(char *input)
{
int i;
char c;
char *tmp;
input = malloc(sizeof(char));
for (i = 0; (c = getchar()) != EOF && c != '\n'; ++i) {
tmp = realloc(input, (i + 2) * sizeof(char));
if (tmp == NULL) {
free(input);
printf("allocation error");
return -1;
}
input = tmp;
input[i] = c;
}
input[i] = '\0';
return 0;
}