Thread: Struct allocation

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    69

    Struct allocation

    Simple question for you guys:

    Given the following struct:

    Code:
    typedef struct mystruct {
        char *c;
        int i;
    } mystruct;
    When declaring an instance of nodeT as follows:

    mystruct *s = malloc(sizeof(nodeT));
    s->c = malloc(sizeof(char));
    s->c = 'a';
    s->i = 5;

    Is i created/stored on the stack or the heap?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,665
    The s pointer itself is on the stack.
    Everything else is on the heap.

    And s->c = 'a'; is a bug.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Code:
    s->c = 'a';
    Do you not get a warning for this? You're assigning a char to char*, so you should get a warning about cast from integer to pointer.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  4. #4
    Registered User ssharish2005's Avatar
    Join Date
    Sep 2005
    Location
    Cambridge, UK
    Posts
    1,732
    and perhaps here as well,

    Code:
    mystruct *s = malloc(sizeof(nodeT));
    What is nodeT, and you are assigning it to mystruct. You are assigning totally to a diffewrent struct type.

    ssharish

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Concatenating in linked list
    By drater in forum C Programming
    Replies: 12
    Last Post: 05-02-2008, 11:10 PM
  2. Help please im stuck
    By ItsMeHere in forum C Programming
    Replies: 7
    Last Post: 06-15-2006, 04:07 AM
  3. Passing pointers between functions
    By heygirls_uk in forum C Programming
    Replies: 5
    Last Post: 01-09-2004, 06:58 PM
  4. problem with structures and linked list
    By Gkitty in forum C Programming
    Replies: 6
    Last Post: 12-12-2002, 06:40 PM
  5. what does this mean to you?
    By pkananen in forum C++ Programming
    Replies: 8
    Last Post: 02-04-2002, 03:58 PM