0

I am trying to store character as well as integer numbers in the same region through character pointer however, I am not getting the intended result. It is displaying only characters. Here, I have created a character pointer which should contain atleast both characters and integers, then should display them properly.

int main()
{
char c,store[30];
char *p=malloc(30);
 int choice,i=0,n;

 p=store;
while(1)
{
 printf("\n********Menu**********");
 printf("\n1.Enter a character");
 printf("\n2.Enter a Number");
 printf("\n3.Enter a double");
 printf("\n4.Display the values");
 printf("\n0.Exit");
 printf("\nEnter your choice:");
 scanf("%d",&choice);

 switch(choice)
 {
 case 1:
     printf("\nEnter a character:");
     fflush(stdin);
     scanf("%c",&c);

     *p=c;

     p++;
     break;

 case 2:
     printf("\nEnter a Number");
     scanf("%d",&n);
     *p++=n;
     break;
 case 4:

     *p--='\0';
     for(i=0;store[i];i++)
         printf("%c",store[i]);
     break;

 case 0:
    exit(0);
    break;
 }
}

 getch();
 return 0;
}
2
  • 1
    First of all: Why would you do this??? It's a horrible practice, and shouldn't be done without a lot of extra code to make sure you don't do it wrong. Second: You're doing it badly - in case 2, you should be incrementing p by sizeof(int) and you need a typecast, Third: When you print, you're using %c to print it as a character. If it was an int, print it with %d. Is this an attempted lesson in learning how to use a union? Commented Sep 26, 2013 at 18:40
  • 1
    What do you think *p++ does ? Commented Sep 26, 2013 at 18:44

1 Answer 1

1

You can't simply write doubles and int into a char array.

However with following you could see 0-9 :

case 2:
     printf("\nEnter a Number"); //Just for 0-9   
     scanf("%d",&n);
     *p=n+48; //Convert to ascii
     p++;
     break;
Sign up to request clarification or add additional context in comments.

2 Comments

What you will receive if user enter, for example, 11 as number?
@DanilAsotsky ascii corresponding to 11+48, w.r.t my post

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.