简体   繁体   中英

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!

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM