What I want to do here is, I want to read input from a user with scanf into a char pointer and dynamically allocate memory as more input is read.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *ptr, temp;
int i, ind = 0;
ptr = malloc(sizeof(char) * 2);
while (scanf(" %[^\n]c", &temp) != EOF)
{
ptr[ind] = temp;
ind++;
ptr = realloc(ptr, sizeof(char) * (ind + 1));
}
for (i = 0; i < 5; i++)
printf("%c", *(ptr + i));
return 0;
}
My code is like this, however it either throws a segmentation error (when the number of character in one line is more than 8) or does not even print any characters. What am I missing? Thanks in advance.
2 * sizeof(char)doesn't do exactly what you think, you only allocate memory for 2 characters.reallocto get more as characters are read.scanf()is the wrong function to use then:)mflag to scanf is for:scanf("% m[^\n]", &ptr);