Thread: Pointer Array Question

  1. #1
    Registered User
    Join Date
    Jul 2008
    Posts
    4

    Pointer Array Question

    I'm still pretty new to C programming and I was wondering if someone could tell me why the following code results in a seg fault:

    Code:
    typedef struct mob mob_t;
    struct mob {
       char *names[10 * sizeof(char)];
    };
    
    main() {
       mob_t *mob; 
       mob->names[0] = "Steve the Monster";
    }
    Any advice/input is greatly appreciated, thanks!

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Because mob doesn't point anywhere.
    Code:
       mob_t mob;
       mob.names[0] = "Steve the Monster";
    But that's probably not what you really want anyway.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Registered User
    Join Date
    Jul 2008
    Posts
    4
    It's not exactly, mob has to be a pointer but I'm not sure how to implement it in such a way..

  4. #4
    Registered User
    Join Date
    Sep 2007
    Posts
    1,012
    Code:
    char *names[10 * sizeof(char)];
    Semantically this doesn't make sense. The number in the [] brackets is how many elements you want in your array. In this case it is the number of strings (ie, names) you want. Using sizeof to compute the number of elements you want in an array is normally the wrong thing to do. When you're creating an array, you do not need to tell the compiler how big each element is; it already knows.

    Incidentally, sizeof(char)---that is, the size of a character---is always 1. You might have been thinking sizeof(char *), although that is still not right as I described above.

  5. #5
    Registered User
    Join Date
    Jul 2008
    Posts
    4
    Ah, thanks for clearing that up for me, I get confused in differentiating malloc-ing pointers and just setting the array size.

    But if I change that to just

    Code:
    char *names[10];
    I still need to know how to implement with the mob pointer somehow

  6. #6
    Registered User
    Join Date
    Jul 2008
    Posts
    4
    I just figured out a solution, thanks to everyone who replied though!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. pointer of array of class
    By 11moshiko11 in forum C++ Programming
    Replies: 5
    Last Post: 04-05-2008, 09:58 AM
  2. Direct3D problem
    By cboard_member in forum Game Programming
    Replies: 10
    Last Post: 04-09-2006, 03:36 AM
  3. array pointer question
    By Hoser83 in forum C Programming
    Replies: 5
    Last Post: 02-03-2006, 11:19 AM
  4. Passing pointers between functions
    By heygirls_uk in forum C Programming
    Replies: 5
    Last Post: 01-09-2004, 06:58 PM
  5. A question between Array and Pointer
    By Unregistered in forum C++ Programming
    Replies: 16
    Last Post: 08-05-2002, 09:13 AM