user1005253
user1005253

Reputation: 404

Struggling with printing values from structures in C

I'm having a bit of trouble with structures in C. I think the problem is with pointers. Here is what my program is supposed to do; Read an input data, such as this;

Name: Hello
Gender: Male
Age: 60

Name: Hello1
Gender: Male
Age: 13

Name: Hello2
Gender: Female
Age: 10

Name: Hello3
Gender: Male
Age: 20

I want the program to read the the words after the ':', e.g Hello and put that value into a structure. So an index[1] of a structure should contain hello, male, 60, for example.

When I print values inside the while loop, it is printing fine. But when I try and print values of structures outside the while loop, it does not work. I get this as output;

¿6Q ¿6Q  60
 ↑  13
 æ £  10
 §☺  ☺  20

It is printing the age for each element, but not any of the others. I been struggling with this for a while, and have no idea why this is the case. Thankyou for your help; Here is my code:

Upvotes: 0

Views: 131

Answers (1)

Aleks G
Aleks G

Reputation: 57346

First off, please do mark the homework as homework.

Second, as Mr Lister indicated, you are allocating variable line to be 80 chars long, but you're reading up to 100 characters from the file into it - with long lines this will cause problems. You should read no more than 79 characters (leaving 1 for the \0 at the end).

Now about "printing", I think your problem is in these lines:

p[nameIndex].name = (char*)malloc(sizeof(line));
p[nameIndex].gender = (char*)malloc(sizeof(line));
p[nameIndex].age = (char*)malloc(sizeof(line));

As line is essentially a char *, sizeof(line) will not give you the results you're expecting. Instead, you should use strlen function - and not here but rather at the place where you're copying the data. Your code should look something like this:

switch(i)
{
    case 1:
        p[nameIndex].name = (char*)malloc(strlen(tmp) + 1);
        strcpy(p[nameIndex].name, temp);
        break;
    case 2:
        p[nameIndex].gender = (char*)malloc(strlen(tmp) + 1);
        strcpy(p[nameIndex].gender, temp);
        break;
    case 3:
        p[nameIndex].age = (char*)malloc(strlen(tmp) + 1);
        strcpy(p[nameIndex].age, temp);
        break;
    default:
        break;
}

Of course, this is assuming that each character takes 1 byte of storage. Otherwise, you should use (strlen(tmp) + 1) * sizeof(char) to get the right allocation.

Upvotes: 1

Related Questions