Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 135,998 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 2,394 people online right now. Registration is fast and FREE... Join Now!




Pointer help!

 
Reply to this topicStart new topic

Pointer help!

darkstar2466
30 Nov, 2006 - 04:02 AM
Post #1

New D.I.C Head
*

Joined: 30 Nov, 2006
Posts: 2


My Contributions
Hi, my assignment is to read in a file from a command line parameter and use malloc to allocate memory for the contents. I declared three double pointers in my main function to pass into the read_file() method and every time I run the program, it seg faults. Can someone please help me out with my use of pointers. I don't think I have it quite right in dereferencing the pointers.

Here is my code:

CODE

int main(int argc, char *argv[])
{
        int **scores;
        char **ids, **labels;

        read_file(argv[1], &labels, &ids, &scores);

        return 0;
}

void read_file(char *argv, char ***labels, char ***ids, int ***scores)
{
        FILE *fp;
        int numrows, numcols, i, j;
        char line[256], *ptr;

        fp = fopen(argv, "r");
        fgets(line, 256, fp);
        numrows = atoi(strtok(line, " "));
        numcols = atoi(strtok(NULL, " "));

        *labels = (char**)malloc(numcols * sizeof(char));
        fgets(line, 256, fp);

        ptr = strtok(line, " ,");
        *labels = (char**)malloc(numcols * sizeof(char*));
        for(i = 0; i < numcols; i++)
        {
                *labels[i] = (char*)malloc(strlen(ptr)+1);
                strcpy(*labels[i], ptr);
                ptr = strtok(NULL, " ,");
        }

        *ids = (char**)malloc(numrows * sizeof(int*));
        *scores = (int**)malloc(numrows * sizeof(int*));
        for(i = 0; i < numrows; i++)
        {
                fgets(line, 256, fp);
                ptr = strtok(line, " ,");
                *ids[i] = (char*)malloc(strlen(ptr)+1);
                strcpy(*ids[i], ptr);
                *scores[i] = (int*)malloc((numcols-1) * sizeof(int));
                for(j = 0; j < numcols - 1; j++)
                        *scores[i][j] = atoi(strtok(NULL, " ,"));
        }
}


Thanks a bunch,

Gautam


User is offlineProfile CardPM
+Quote Post

darkstar2466
RE: Pointer Help!
30 Nov, 2006 - 02:01 PM
Post #2

New D.I.C Head
*

Joined: 30 Nov, 2006
Posts: 2


My Contributions
Never mind, I fixed it.
User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 12/1/08 12:00PM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month