Thread: problem about structures..

  1. #1
    Registered User nyekknyakk's Avatar
    Join Date
    Aug 2010
    Posts
    35

    problem about structures..

    hello, everyone! i have a problem about my code. it automatically crashes after a user typed an info, ie, name, into the program. is there something wrong with the way i get information from the user?

    here's my code:
    Code:
    	printf("Name...");
    	gets(dB[top]->name);
    	printf("Age...");
    	scanf("%d", &(dB[top]->age));
    	printf("Sex...");
    	scanf("%c", &(dB[top]->sex));
    	printf("Height...");
    	scanf("%f", &(dB[top]->height));
    	printf("Weight...");
    	scanf("%f", &(dB[top]->weight));	
    }
    thanks for those who'll help!
    Last edited by nyekknyakk; 09-15-2010 at 10:05 AM.

  2. #2
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    Code:
    struct person *dB[SIZE];
    .
    .
    .
    gets(dB[top]->name);
    First of all, you should NEVER use gets. Period.
    Second, you have an array of pointers but the pointers don't point anywhere. You need to allocate memory for each of them before you read into them.

  3. #3
    Registered User nyekknyakk's Avatar
    Join Date
    Aug 2010
    Posts
    35
    hi! how will i allocate memory?
    is this the right way?

    Code:
    	(struct person *)malloc(sizeof(dB));	 //is this right?
    Last edited by nyekknyakk; 09-15-2010 at 10:05 AM.

  4. #4
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    Quote Originally Posted by nyekknyakk View Post
    hi! how will i allocate memory?
    is this the right way?

    Code:
    	(struct person *)malloc(sizeof(dB));	 //is this right?
    No, this would be better:
    Code:
    dB[0] = malloc(sizeof(*dB[0]));
    dB[1] = malloc(sizeof(*dB[0]));
    dB[2] = malloc(sizeof(*dB[0]));
    etc...
    You don't need to cast the return value of malloc, and you need the size of your structure, not the size of your array.
    bit∙hub [bit-huhb] n. A source and destination for information.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with structures and seg fault
    By grifan526 in forum C Programming
    Replies: 3
    Last Post: 04-15-2010, 05:29 PM
  2. Problem filling an array of structures
    By bluetxxth in forum C Programming
    Replies: 7
    Last Post: 03-11-2010, 02:29 AM
  3. Getting illegal case error
    By scmurphy64 in forum C Programming
    Replies: 2
    Last Post: 09-17-2009, 10:35 AM
  4. Replies: 26
    Last Post: 06-11-2009, 11:27 AM
  5. Bin packing problem....
    By 81N4RY_DR460N in forum C++ Programming
    Replies: 0
    Last Post: 08-01-2005, 05:20 AM