prajwal sanket
prajwal sanket

Reputation: 13

how to store characters in pointer using getchar?

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void main(){
   int c;
   char *p=malloc(50*sizeof( char ));
   //char *p;
   while((c = getchar()) != '\n' )
   {
       *p++ = c;
       *p='\0';
        //      printf("%s",p);
   }
   printf("\nThis is outside while %s",p);
}

I am not able to get output outside while,please help!

Upvotes: 0

Views: 846

Answers (1)

R Sahu
R Sahu

Reputation: 206577

Use an index. That will allow you to modify the contents of the string without changing the value of the pointer. You can also use the index to prevent access to invalid data.

int c;
int i = 0;

char *p=malloc(50*sizeof( char ));
while((c = getchar()) != '\n' && i < 49 )
{
   p[i] = c;
   ++i;
}

p[i] = '\0';
printf("\nThis is outside while %s",p);

Upvotes: 1

Related Questions