Thread: Menu in a restaurant.what happens to the pointer p? why does it return its value?

  1. #1
    Registered User
    Join Date
    Jun 2018
    Posts
    1

    Menu in a restaurant.what happens to the pointer p? why does it return its value?

    hello everyone!
    i wanted to ask why this program prints "sugared turkey" twice.
    why does the pointer p* still lives in the program even though it was declared locally?
    thank you very much for your support.
    Idan perry.

    Code:
    #include <stdio.h>
    #include <string.h>
    enum type {H=1/* herbivore /,C=2/ carnivore */,
        S=4/* sweet tooth /,D=8/ Drinker */};
    
    
    char * dish(int x)
    {
        char buf[100];char *p = buf;*p=0;
        if(x & D)strcat(p,"rum-soaked ");/H|D/
        if(x & S)strcat(p,"sugared ");/C|S/
        if(x & C)strcat(p,"turkey ");/C|S/
        if(x & H)strcat(p,"broccoli ");/H|D/
        return p;
    }
    int main()
    {
        char *p = dish(C|S);
        char *c = dish(H|D);
    
    
        printf("please pass the %s and the %s.",p,c);
        return 0;
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > why does the pointer p* still lives in the program even though it was declared locally?
    It doesn't.

    That it "works" for you in this instance is down to pure dumb luck and nothing else.

    Sooner or later, it will stop working.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    May 2012
    Location
    Arizona, USA
    Posts
    948
    The program doesn't even compile for me so it has no output. "C" and "D" are undeclared, and you have syntax errors in the "dish()" function.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Return pointer to a vector of objects as a function return
    By Adaptron in forum C++ Programming
    Replies: 14
    Last Post: 04-07-2016, 09:23 AM
  2. Return to main menu issue
    By ulti-killer in forum C Programming
    Replies: 6
    Last Post: 11-04-2012, 11:13 AM
  3. Menu for Restaurant Program.
    By francozb92 in forum C Programming
    Replies: 4
    Last Post: 04-03-2011, 09:49 AM
  4. return to menu problem
    By spikestar in forum C Programming
    Replies: 3
    Last Post: 08-18-2009, 01:32 PM
  5. Return to Menu
    By Unregistered in forum C++ Programming
    Replies: 1
    Last Post: 11-21-2001, 07:46 PM

Tags for this Thread