problem with a function!

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • chara3
    New Member
    • Mar 2010
    • 1

    problem with a function!

    I've been developing a programm similar to the stable marriage problem.
    I've just started but there is something wrong with the code. The 3rd argument of function saveToFile doesn't work. Can somebody help me?


    Code:
    #include <stdio.h>
    #include <io.h>
    #include <stdlib.h>
    #include <string.h>
    //using namespace std;
    void saveToFile(char* fileName, int numberOfPersons, char *namesOfPersons)
    {
        FILE *myFile;
        if((myFile=fopen(fileName,"w"))==NULL)
        {
            printf("Cannot write file... Using already stored lists.");
            exit(-1);
        }
        else
        {
            for(int i=0;i<numberOfPersons;i++)
            {
                    fprintf(myFile, "%s\n",&namesOfPersons[i]);
            }
            fclose(myFile);
        }
    }
    
    void dataEntry(char* requestFor)
    {
        int numberOfPersons;
            
        printf("How many %ss? ",requestFor);
        scanf("%d",&numberOfPersons);
          
        char *namesOfPersons[numberOfPersons]; //Array of character array(string);
        
        //Ask for Person names    
        for(int i=0;i<numberOfPersons;i++)
        {
          printf("%s name %d: ",requestFor,i);
          scanf("%s",&namesOfPersons[i]);      
        }
           saveToFile(strcat(requestFor,"List.txt"), numberOfPersons, &namesOfPersons);
    }
    int main(int argc, char *argv[])
    {
        dataEntry("Teacher");
        dataEntry("Student");
        dataEntry("Diplwmatikes");
        system("PAUSE");
        return EXIT_SUCCESS;
    }
    I can't put it in code tags for some reason!
  • donbock
    Recognized Expert Top Contributor
    • Mar 2008
    • 2427

    #2
    Whenever you pass an array you need to declare the parameter as a pointer to the first element in the array. The first element is a null-terminated string; that is, a char*. Your parameter has to be a pointer to a char* ... or a char**.

    Function dataentry defines automatic variable namesOfPersons to hold the array of pointers, but it doesn't allocate any memory to hold the strings pointed to by the array elements. You should review the operation of the "%s" feature of scanf.

    Comment

    Working...