I have an assignment in which I have to accept an input from the user. I can't use a linked list, only an array, so my plan is:
Alloc some memory.
If we need to realloc, meaning that I reached the number of cells allocated:
Try to realloc. If successful, great.
If we couldn't realloc, print input, free memory and realloc then.
I can't really decide about the command that tells me how did I reach the end of memory allocated and that's why I need your help. I wrote:
if (i==(MAX_CHARS_INPUT-1))
But I am not sure about it.
The code:
#include <stdio.h>
#include <stdlib.h>
#define MAX_CHARS_INPUT 200
#define D_SIZE 2
void printWithMalloc(){
int charSize=1;
int *ptr=malloc(MAX_CHARS_INPUT*sizeof(charSize));
int i=0, j=0, c;
printf("please enter a string\n");
while ((c=getchar())!=EOF && c!='\n')
{
ptr[i++]=c;
if (i==(MAX_CHARS_INPUT-1)) /*if we need to realloc*/
{
int *temp=realloc(ptr,D_SIZE*MAX_CHARS_INPUT*sizeof(charSize));
if (temp==NULL) /*realloc failed*/
{
printf("you wrote:\n");
while(j<=i)
putchar(ptr[j++]);
free(ptr);
ptr=(int*)malloc(MAX_CHARS_INPUT*sizeof(charSize));
}
else
ptr=temp;
}
}
}
int main(){
printWithMalloc();
return 0;
}
Thank you!
sizeof(charSize)will give you the size of an int since harSize is an int. Instead, just dosizeof(char)sizeof(char)is by definition 1.ptris a buffer ofints, notchars.sizeof(charSize)may seem confused but it is (perhaps unintentionally) correct. Usesizeof *ptrinstead, as that will always work, especially if you ever change the type ofptr.