I'm still very new to C and get multiple error messages in my code and it would be nice if someone could explain these error messages to me.
My code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char newINPUT;
char* INPUT = (char*)malloc(1 * sizeof(char));
while((INPUT = getchar()) =! EOF)
char* newINPUT = (char*)realloc(INPUT, 2* sizeof(INPUT));
if(newINPUT =! NULL)
{
INPUT = newINPUT;
}
else
{
free(INPUT);
printf("Out of memory!");
}
return 0;
}
What this shall do is: It should allocate some memory and read what you type. When there is no allocated memory left it should reallocate double as much memory as has been alocated before.
Error messages: warning line 13(that line with while): assignement makes pointer from integer without cast (enabled as default) error line13: lvalue required as left operand of assignement error line14: expected expression before 'char' warning line 17: same as line 13.
Would be nice if someone could explain that to me. Thanks!
EDIT: Thanks for all the answers so far! They truly helped me in understanding malloc und realloc. I've tried another own version yesterday, but I'm not sure if the allocated memory works right since I can't test it with an input large enough. Would that work (syntaxwise) with the realloc and the doubling?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int *READ; //input
READ = malloc(sizeof(int));
while ((*READ = getchar()) != EOF)
{
if (READ) //if read not null so memory is enough
{
putchar(*READ);
}
else
{
int x;
int* extendedREAD = realloc(READ, (x*2));//expression for "double as much as before"????
if (extendedREAD = NULL) // looking if there s enough memory
{
printf("Error, not enough memory!");
}
x = x * 2;
}
}
return 0;
}
/*
Zeichen einlesen - checken ob eof, wenn nein, dann speicher ausreichend? nein dann vergräßern, sonst zeichen dazuschreiben, dann wieder vonvorne)
*/
Thank you!