1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Development structs in c

Discussion in 'Software' started by ocha, 31 Oct 2008.

  1. ocha

    ocha Minimodder

    Joined:
    29 Dec 2001
    Posts:
    452
    Likes Received:
    0
    can anyone help with the code below:

    Code:
    #include <stdio.h>
    #include <string.h>
    int main()
    {
    	struct Person
    	{
    		char name[30] ;
    		int  age      ;
    		int  regNo    ;
    		int  wage     ;
    	} ;	
    
    	struct Person emp1 ;
    	struct Person emp2 ;
    
    	scanf("%s%i%i%i", emp1.name,  emp1.age, emp1.regNo, emp1.wage) ;
    	strcpy(emp2.name, emp1.name) ;
    	emp2.regNo = 666 ;
    	emp2.wage = emp1.wage * 2 ;
    	printf("%s %i %i %i\n", emp1.name,  emp1.age, emp1.regNo, emp1.wage) ; 
    	printf("%s %i %i %i\n", emp2.name,  emp2.age, emp2.regNo, emp2.wage) ;
    	
    	return 0 ;
    }
    This is returning a segmentation fault when I try it on a redhat server and a bus error on my mac, can anyone tell me why, I am trying to learn C programming and it's got me a bit stuck

    Thanks
     
  2. RTT

    RTT #parp

    Joined:
    12 Mar 2001
    Posts:
    14,120
    Likes Received:
    74
    Scanf expects pointers :)

    Post back if that doesn't help you -- are we doing your homework? ;)

    hint: &
     
  3. ocha

    ocha Minimodder

    Joined:
    29 Dec 2001
    Posts:
    452
    Likes Received:
    0
    Thanks RTT, I have actually just realised I did and metaphorically kicked myself for it. Rather a stupid mistake.

    Some module work for uni that I just couldn't work out, I thought I wouldn't be able to and didn't want to wait until Monday to ask a lecturer.

    Thanks for your help.
     
  4. RTT

    RTT #parp

    Joined:
    12 Mar 2001
    Posts:
    14,120
    Likes Received:
    74
    Easily done :) I'd tidy it up as follows

    Code:
    #include <stdio.h>
    #include <string.h>
    int main()
    {
    	struct Person
    	{
    		char name[30];
    		int  age, regNo, wage;
    	} emp1, emp2;	
    
    	scanf("%s %i %i %i", &emp1.name, &emp1.age, &emp1.regNo, &emp1.wage);
    
    	strcpy(emp2.name, emp1.name);
    	emp2.regNo = 666;
    	emp2.wage = emp1.wage * 2;
    
    	printf("%s %i %i %i\n%s %i %i %i\n", emp1.name, emp1.age, emp1.regNo, emp1.wage, emp2.name, emp2.age, emp2.regNo, emp2.wage); 
    
    	return 0;
    }
    
    You could also improve it by making an array of Persons and loop over them to do the output stage rather than having two identical printf()s or one big long one.
     
    Last edited: 31 Oct 2008
  5. ArcSpark

    ArcSpark Did I let the magic smoke out?

    Joined:
    10 Jan 2008
    Posts:
    75
    Likes Received:
    0
    Shouldn't emp1.name already be a pointer since an index is not specified into the array. Is scanf expecting a double pointer, or am I just missing something?
     

Share This Page