tags:

views:

68

answers:

2
struct match
{
    char men[64];
    char women[64];
    char menNum[1000];
    char woNum[1000];
};

void printOut();
int matchMaking(struct match* p, struct match* q, int k);
int main(void)
{
    FILE* fin;
    FILE* fout;
    fin = fopen("input.txt", "r");
    fout = fopen("out.txt", "w");
    int matchNum = 0;
    int size;
    int i;
    int j;
    int a;
    struct match* ptrName;
    struct match** ptrNum;
    char* str;
    char temp[800];

    if(fin == NULL)
        printf("Cannot Find File");

    fgets(temp, 800, fin);
    str = (char*)malloc(sizeof(char));
    str = (char*)strtok(temp, " \n");
    size = atoi(str);
    printf("Size = %d\n", size);

    ptrName = (struct match*)malloc(size*sizeof(struct match));
    ptrNum = (struct match**)malloc(size*sizeof(struct match*));

    for(i = 0; i < size; i++)
    {

        fgets(temp, 800, fin);
        str = (char*)strtok(temp, " \n");
        matchNum = atoi(str);
        printf("Match Num = %d\n", matchNum);
        fgets(temp, 800, fin);
        strcpy(ptrName->men, temp);
        printf("Name = %s\n", ptrName->men);
        fgets(temp, 800, fin);
        strcpy(ptrName->women, temp);
        printf("Name = %s\n", ptrName->women);

        for(j = 0; j<matchNum; j++)
        {
            fgets(temp, 800, fin);
            strcpy(ptrNum[j]->menNum, temp);
            printf("Men Num = %d\n", ptrNum[j]->menNum);
        }

when debugging I keep getting a segmentation fault as an error

A: 

You allocate an array of pointers, but you never actually set those pointers to anything! Your call to strcpy(ptrNum[j]->menNum, temp); will write to a random address since each one of your entries in ptrNum[] is uninitialized.

EboMike
+2  A: 

Coarsely, I'd say the problem is here:

ptrNum = (struct match**)malloc(size*sizeof(struct match*));

What you really want is enough memory for size number of struct match, not size number of pointers. Then you want to index into that space.

Effectively, you should do something like

struct match* ptrNum = malloc(size*sizeof(struct match));

This gives you a block of memory for size number of the structs and gives you a pointer to the first one. You can use the shorthand "array" notation to index into this memory, so match[0] gives you the struct at position 0 in the "array" and match[j] gives you record at the j-th position.

Also note, match[j] gives you back the actual memory, so you won't want to use pointer notation:

strcpy(ptrNum[j].menNum, temp);
Mark E
thank you that helped out a lot, i was getting ready to throw my CS1 book through my monitor
Chris