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

Struct Array

Discussion in 'C' started by micmac700, Dec 13, 2006.

  1. micmac700

    micmac700 New Member

    Joined:
    Dec 13, 2006
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    in my .c file i have a struct atop of the program defined as follows:
    Code:
    #define MAX 10
    int curtab;
    
    static struct tab {
    	int count;
    	int use;
    } tab[MAX];
    
    with the initial function following it like so:
    Code:
    int tab_create(int init_count)
    {
           int i;
           for(i=0; i < MAX; i++)
    	{
    		if(tab[i].use != 1)
    		{
    			tab[i].use = 1; /* true */
    			tab[i].count = init_count;
    			curtab = i;
    			i = MAX; /* break */
    		}
    	}
           return (curtab);
    }
    
    but I find I receive a Seg-Fault error at
    Code:
    if(tab[i].use != 1)
    Why does this occur?
     
  2. DaWei

    DaWei New Member

    Joined:
    Dec 6, 2006
    Messages:
    835
    Likes Received:
    5
    Trophy Points:
    0
    Occupation:
    Semi-retired EE
    Location:
    Texan now in Central NY
    Home Page:
    I see no reason for it to seg fault. Perhaps there's some undefined operation in "main", which you don't show?
     
  3. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,287
    Likes Received:
    364
    Trophy Points:
    83
    I guess you are passing tab_create a value greater than some upper limit value
     
  4. DaWei

    DaWei New Member

    Joined:
    Dec 6, 2006
    Messages:
    835
    Likes Received:
    5
    Trophy Points:
    0
    Occupation:
    Semi-retired EE
    Location:
    Texan now in Central NY
    Home Page:
    Still, the array bounds are constrained by MAX in the loop. If tab_create is some goshawful unitialized number, it should still fit in an int, or the compiler would complain. Do you have a good compiler with all warnings and errors turned on? You really, at this point, should show "main", since all the code that you show is functional on my system, with my own "main", of course.

    You will probably find MAX defined elsewhere in the standard library (a thangy to return the max of two values), but your #define should override.
     

Share This Page