Thread: How to edit the values of an array in a struct?

  1. #1
    Registered User
    Join Date
    Jan 2011
    Posts
    37

    How to edit the values of an array in a struct?

    Hi. This code:

    Code:
    struct node {
    	int data[10];
    };
    
    int main()
    {
    	struct node* head;
    	int x;
    	
    	head->data[0] = 42;
    	x = head->data[0];
    	
    	printf(" x is %d\n",x);
    }
    results in this output:
    " x is 42
    Segmentation fault"

    Explanation and solution appreciated

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    You never allocate memory for head. You need to make it an actual struct node (no * pointer business) and use the . operator instead of ->, or you need to malloc space for a struct node and have head point to the malloc'ed memory.

  3. #3
    Registered User
    Join Date
    Jan 2011
    Posts
    37
    Quote Originally Posted by anduril462 View Post
    You never allocate memory for head. You need to make it an actual struct node (no * pointer business) and use the . operator instead of ->, or you need to malloc space for a struct node and have head point to the malloc'ed memory.
    Ahhh, i did leave out that essential malloc()... But why use the . instead of ->?

  4. #4
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    . is for a struct (per my first suggestion, dropping the * and using a struct), -> is for a pointer to a struct.

  5. #5
    Registered User
    Join Date
    Mar 2011
    Posts
    278
    Quote Originally Posted by bluej322 View Post
    But why use the . instead of ->?
    Good question - you tell us after you look it up ;-)

    It has to do with whether you are dealing with an actual structure (typically one that is locally declared) or a pointer to a structure (as it would typically be if you passed it in as a parameter from a calling function)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Assigning values to struct array or linked list problem?
    By kalamram123 in forum C Programming
    Replies: 1
    Last Post: 04-07-2011, 12:38 PM
  2. default values in struct
    By taurus in forum C Programming
    Replies: 1
    Last Post: 10-04-2009, 05:43 AM
  3. Storing values from Edit Box into an array
    By E_I_S in forum C++ Programming
    Replies: 10
    Last Post: 06-05-2008, 06:24 AM
  4. Struct Values
    By Muphin in forum C++ Programming
    Replies: 5
    Last Post: 08-13-2005, 09:24 PM
  5. Get all values from a struct
    By Muphin in forum C++ Programming
    Replies: 10
    Last Post: 08-05-2005, 08:47 AM