Thread: Help with function declaration

  1. #1
    Unregistered
    Guest

    Help with function declaration

    Hi all,
    I have this code that I want to turn into a separate function and need help with the function declaration.
    The function reads data from a file into an array of structures
    Here is the struct def and the function.

    struct Data {
    char *string;
    int num;
    };


    for(i=0;i<numofelem;i++)
    {
    scanf("%s %d",tmp,&people[i].num);
    people[i].string=(char *)malloc(sizeof(char)*(strlen(tmp)+1));
    strcpy(people[i].string,tmp);
    }
    Now should the declaration be void readdata(char* string, int num) ?

    Thanks in advance.

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    You could use something like this:

    void readData ( struct Data *people, FILE *inputFile, int elements );

    A pointer to the array of structs, the file to read from, and the number of elements in the array so that you know where to stop reading. An additional option would be to include a return value which reports errors to the calling function.
    Code:
    for(i=0;i<numofelem;i++) 
    { 
    scanf("%s %d",tmp,&people[i].num); 
    people[i].string=(char *)malloc(sizeof(char)*(strlen(tmp)+1)); 
    strcpy(people[i].string,tmp); 
    }
    Your use of malloc here is very unsafe and more confusing than it has to be. The actual call would be safer and less crufty like so:

    people[i].string = malloc ( sizeof tmp );

    And every time you use malloc, never forget to check the return value. Trying to strcpy something into a NULL pointer will give you problems every time. And of course, don't forget that scanf reads from stdin and not a file. You'll need to use fscanf if you want to send a file to the function and read from it.

    -Prelude
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  2. doubt in c parser coding
    By akshara.sinha in forum C Programming
    Replies: 4
    Last Post: 12-23-2007, 01:49 PM
  3. <Gulp>
    By kryptkat in forum Windows Programming
    Replies: 7
    Last Post: 01-14-2006, 01:03 PM
  4. Problem with Visual C++ Object-Oriented Programming Book.
    By GameGenie in forum C++ Programming
    Replies: 9
    Last Post: 08-29-2005, 11:21 PM
  5. structure vs class
    By sana in forum C++ Programming
    Replies: 13
    Last Post: 12-02-2002, 07:18 AM