Thread: Returning a vaule loses the last one

  1. #1
    Registered User
    Join Date
    Jan 2003
    Posts
    4

    Question Returning a vaule loses the last one

    Hi there, Im having a bit of a problem returning values from a function.

    Basically I want to return a value from an array but when i return I call the function the second time it overrights the first value even though they are stored in two different variables.
    Can anyone please help???


    This is the function:

    char inputMenuChoice()
    {
    char returnedName;
    int MenuChoice;
    scanf("%d", &MenuChoice);
    if (MenuChoice == 1)
    {
    strcpy(returnedName, Name[0]);
    }
    if (MenuChoice == 2)
    {
    strcpy(returnedName, Name[1]);
    }
    if (MenuChoice == 3)
    {
    strcpy(returnedName, Name[2]);
    }
    if (MenuChoice == 4)
    {
    strcpy(returnedName, Name[3]);
    }
    if (MenuChoice == 5)
    {
    strcpy(returnedName, Name[4]);
    }
    return returnedName;
    }


    and it is called like so:

    typeFromConvert = inputMenuChoice();
    typeToConvert = inputMenuChoice();

  2. #2
    Registered User sean345's Avatar
    Join Date
    Mar 2002
    Posts
    346
    You do not need to use strcpy if you are only using a char. It is only for strings.

    Just do this:
    Code:
    ReturnedName = Name[x];
    I think this is what you are trying to do.

    It should not overwrite it like you are saying unless you are using pointers and only passing the address. Can you be more specific and post your code using code tags.

    - Sean
    If cities were built like software is built, the first woodpecker to come along would level civilization.
    Black Frog Studios

  3. #3
    Registered User
    Join Date
    Jan 2003
    Posts
    4
    I tried making returnedName an array but that just kept giving me a NULL value

    Also Im not using pointers because i cant.

  4. #4
    Registered User
    Join Date
    Apr 2002
    Posts
    1,571
    Originally posted by RatBoy
    I tried making returnedName an array but that just kept giving me a NULL value

    Also Im not using pointers because i cant.
    The way sean told you to do it should work. Remember a function can NEVER return an array. It can return lots of other things but not array's. Just return the single character like you had but just don't use strcpy because it is unnecessary. Just use a simple assignment.
    "...the results are undefined, and we all know what "undefined" means: it means it works during development, it works during testing, and it blows up in your most important customers' faces." --Scott Meyers

  5. #5
    Casual Visitor
    Join Date
    Oct 2001
    Posts
    350
    See if you can work with this, though I'm not sure it's what you need.
    Code:
    #include <stdio.h>
    
    char getChoice(void);
    
    
    int main(void)
    {
        char letter;
        char buffer[10];
        int count;
    	
        count= 0;
    
        do
        {
    	  
           letter = getChoice();
           buffer[count++] = letter;
    	
        }while(count != 10);
    
        buffer[count] = '\0';
    
        for(count = 0; buffer[count] != '\0'; count++)
        {
    	letter = buffer[count];
    	switch(letter)
    	{
                case '1': /* do something with '1' */ break;
                case '2': /* do something with '2' */ break;
                case '3': /* do something with '3' */ break;
                case 'A': /* do something with 'A' */ break;
               case 'B': /* do something with 'B' */ break;
              default: 
            /* output error message or
    	    do some action         */ break;
           };
        }
    
        printf("The choices made were: %s\n\n", buffer);
    
        return 0;
    }
    
    char getChoice(void)
    {
        char choice, trash;
        static char *menu = "1> item 1\n"
                            "2> item 2\n"
                            "3> item 3\n"
                            "A> item A\n"
                            "B> item B\n"
                            "\n\n-> ";
    
        printf("%s", menu);
        scanf("%c%c", &choice, &trash);
        printf("\n");
    
        return choice;
    }
    I've typed too fast and now my fingers are bleeding. :P
    Last edited by ronin; 01-04-2003 at 05:04 PM.

  6. #6
    Registered User
    Join Date
    Jan 2003
    Posts
    4
    I have changed my code to:

    Code:
    char inputMenuChoice()
    {
     char ReturnedName;
     scanf("%d", &MenuChoice);
    
     printf("\n%s", Name[MenuChoice-1]);
     ReturnedName = Name[MenuChoice-1];
    
     return ReturnedName;
    }
    when i run my program and it gets to the function it prints out
    Code:
    printf("\n%s", Name[MenuChoice-1]);
    grand but when it exits the function and goes to print out the value outside of the function I get weird stuff like BORLAND C VERSION

    Im going mad over this cuz i have tried everything that i can think of....oh btw im a newbie incase youu didn't get it

  7. #7
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    What is the Name variable for? Can you show a bit more code so I can see what your trying to do with it.

    Also, you're returning a single char, so when you print it, you need to do so like this:
    >printf("%c\n", returnedValue);
    There are other ways, but basically, I'm showing you that using %s will not work. Again, I need to understand your code better before advising further.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  8. #8
    Registered User
    Join Date
    Jan 2003
    Posts
    4

    Question Thank You

    Ok i decided to scrap the idea altogether but thank you for your help all of you. After scrapping the idea though i decided to do something else and now im having the same problem

    Code:
    	char *NameArray[5] = {""};
                    float RateArray[5];
                    int j;
    	float Rate;
    	char Name[10];
    
    	clrscr();
    
    	ratesFile = fopen("rates.txt", "r");
    
    	if (ratesFile == NULL)
    	{
    	 puts("Error opening file\n");
    	 exit(0);
    	}
    
    	while ( fscanf ( ratesFile, "%f%s", &Rate, Name ) != EOF )
    	{
    	 RateArray[i] = Rate;
    	 NameArray[i] = Name;
    	 printf("\n%s", Name);
    	 printf("\n%s", NameArray[i]);
    	 i++;
    	}
    
    	for (j=0; j<5; j++)
    	{
    	printf("\n%f", RateArray[j]);
    	printf("\n%s", NameArray[j]);
    	}
    When i run this my output is as follows:

    john
    john
    jack
    jack
    brian
    brian
    paul
    paul
    conor
    conor
    1
    conor
    2
    conor
    3
    conor
    4
    conor
    5
    conor


    does anyone know why the int value is being stored properly and why the string value is getting over written and only storing the last value once i exit the while loop????

    Thank you all for the help last night

  9. #9
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >does anyone know why the int value is being stored properly and why the string value is getting over written
    Because you're storing a pointer to the data, you won't get a unique string with every iteration, you'll store a new pointer to the same string. The end result is that every element of the NameArray points to the same string. To avoid this, make a copy:
    Code:
    while ( fscanf ( ratesFile, "%f%s", &Rate, Name ) != EOF )
    {
      RateArray[i] = Rate;
      NameArray[i] = malloc ( strlen ( Name ) + 1 );
      strcpy ( NameArray[i], Name );
      printf("\n%s", Name);
      printf("\n%s", NameArray[i]);
      i++;
    }
    -Prelude
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Stop GUI Application returning when run
    By DaveHope in forum Windows Programming
    Replies: 7
    Last Post: 06-29-2009, 08:57 PM
  2. Help with struct... not returning correct results.
    By drty2 in forum C Programming
    Replies: 7
    Last Post: 01-18-2009, 11:25 PM
  3. function returning hour in either 12 or 24 hour format
    By stanlvw in forum C Programming
    Replies: 4
    Last Post: 01-01-2008, 06:02 AM
  4. Recursion: base case returning 1, function returning 0
    By yougene in forum C Programming
    Replies: 5
    Last Post: 09-07-2007, 05:38 PM
  5. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM