Hello, first(as always) I want to apologize about my english, it may not be clear enough.
I'm not that good at C programming, and I was asked to read a "string" input with undefined length.
This is my solution
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *newChar();
char *addChar(char *, char);
char *readLine(void);
int main() {
char *palabra;
palabra = newChar();
palabra = readLine();
printf("palabra=%s\n", palabra);
return 0;
}
char *newChar() {
char *list = (char *) malloc(0 * sizeof (char));
*list = '\0';
return list;
}
char *addChar(char *lst, char num) {
int largo = strlen(lst) + 1;
realloc(&lst, largo * sizeof (char));
*(lst + (largo - 1)) = num;
*(lst + largo) = '\0';
return lst;
}
char *readLine() {
char c;
char *palabra = newChar();
c = getchar();
while (c != '\n') {
if (c != '\n') {
palabra = addChar(palabra, c);
}
c = getchar();
}
return palabra;
}
Please, I'd appreciate that you help me by telling me if it's a good idea or giving me some other idea(and also telling me if it's a "correct" use for pointers).
Thanks in advance
EDIT: Well, thanks for you answers,they were very useful. Now I post edited(and I hope better) code, maybe could be useful for someone new to C(like me) and be feedbacked again.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void reChar(char **, int *);
void readLine(char **, int *);
int main() {
char *palabra = NULL;
int largo = 0;
reChar(&palabra, &largo);
readLine(&palabra, &largo);
printf("palabra=%s\n", palabra, largo);
system("pause");
return 0;
}
void reChar(char **lst, int *largo) {
(*largo) += 4;
char *temp = (char*) realloc(*lst, (*largo) * sizeof (char));
if (temp != NULL) {
*lst = temp;
} else {
free(*lst);
puts("error (re)allocating memory");
exit(1);
}
}
void readLine(char **lst, int *largo) {
int c;
int pos = 0;
c = getchar();
while (c != '\n' && c != EOF) {
if ((pos + 1) % 4 == 0) {
reChar(lst, largo);
}
(*lst)[pos] =(char) c;
pos++;
c = getchar();
}
(*lst)[pos] = '\0';
}
PS:
It seem enough to slow increase size of "palabra".
I'm not sure if capture
getchar()
into aint
and then cast it into achar
is the correct way to hadle EOF pitfall