Hi everyone! I've started learning C a couple of months ago and now I'm facing a couple of problems when it comes to dynamic memory.
You see, I was trying to make a program that could read as many characters as the user would type. Everything was working fine but I couldn't print out the whole string. Any suggestions would be very much appreciated
Thanks in advance!
Code:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<string.h>
int main ()
{
char *c = (char*)malloc(sizeof(char));
int x = 0;
do
{
c = (char*)realloc(c, sizeof(char)*(x+1));
*(c+x) = getchar();
x++;
}while (*(c+x) != '\0');
for (int y = 0; y < x; y++ )
{
printf("%c", c[y]);
}
getch();
}