After having so many problems using the scanf() function I decided to search for an alternative to read whole strings (and by whole strings I mean words mixed with white spaces and numbers etc, until a \n is found) from the keyboard. I stumbled upon an interesting bit of code here on stackoverflow.
So I changed that code to be more dynamic, I wanted to allocate memmory after a char input from the keyboard. I got it to work but only with char **a
as an argument and ,in main(), I would call it like this read(&w);
.My idea is to create an argument-less function so that I can use it without having to declare a variable char *w
each time I need to read a string. Here's the code I got:
char *read(char **a) {
int i = 0;
while (1) {
*a = (char *)realloc(*a, (i + 1) * sizeof(char));
scanf("%c", &(*(*a + i)));
if ( *(*a+i) == '\n')
break;
else
i++;
}
*(*a+i) = '\0';
return *a;}
Now i'm trying to modify this function to take no arguments but I'm getting write/read access violation errors :
char *read2() {
int i = 0;
char **a = NULL;
while (1) {
*a = (char *)realloc(*a, (i + 1) * sizeof(char)) // Error here
scanf("%c", &(*(*a + i)));
if (*(*a + i) == '\n') { break; }
else { i++; }
}
*(*a + i) = '\0';
return *a;}
Thanks in advance