I first read one character into int c and I need to allocate memory for it. That is why I am using "sizeof(c)". What am I supposed to put there then?
I first read one character into int c and I need to allocate memory for it. That is why I am using "sizeof(c)". What am I supposed to put there then?
'c' is an int. You need this to test for EOF, but, you want to store a char.
Also, you ought to store the return value of realloc in a temporary as Quzah suggested to avoid that problem if it fails.
The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.
I'm not operating at 100%, but I might work with this.
Code:#include <stdio.h> #include <stdlib.h> int main(void) { char *temp, *input = NULL; size_t i = 0; fputs("Type something: ", stdout); fflush(stdout); for ( ;; ) { int c = getchar(); if ( c == '\n' || c == EOF ) { break; } temp = realloc(input, i + 2/* incoming char and null */); if ( temp ) { input = temp; input[i++] = c; input[i] = '\0'; } else { free(input); break; } } if ( input ) { puts(input); } free(input); return 0; } /* my output Type something: hello world hello world */
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
Read my post again. I explain why you don't need sizeof(c).Originally Posted by caduardo21
Skip the free call there, and just break. Or, set 'input' to NULL after the free. (edit: Oh, and move the 'free' call inside the last if check.) Otherwise you'll end up trying to free your pointer twice.Originally Posted by Dave_Sinkula
But since we're both not operating at full capacity tonight... (heads off for another brew)
[edit=2]
Hehe. We'll get him eventually.Originally Posted by cwr
[/edit]
Quzah.
Last edited by quzah; 08-25-2005 at 09:35 PM.
Hope is the first step on the road to disappointment.
This is 7:15 in the morning, I just came off the shower and I think I finally got it...
I don't need sizeof(c) because that will allocate four bytes and all I need is one byte because a character is always a byte. Is that correct?
I think somebody might have already mentioned this but I didn't read the whole thread so,
input wont be NULL because NULL is never assigned to it.Code:if (input == NULL) return 1;
>input wont be NULL because NULL is never assigned to it.
And if malloc() fails, what will be assigned to it?
Yeah, kind of like when I said "You are still originally malloc'ing sizeof(int), but you only need 1 byte for the first char." above.Originally Posted by caduardo21