Thread: c struct with pointer

  1. #1
    Registered User
    Join Date
    Jul 2017
    Posts
    2

    c struct with pointer

    Hi,
    please help
    I have a struct with a pointer to another struct

    *********************
    Code:
    typedef struct f{
        
        fl *fl;
        f *next;
    }f;
    typedef struct fl{
        
        int i;
    
    
    }f;
    ************************
    my problem is when i try to add a new item
    i initiate a new fl struct with malloc
    *****************************
    Code:
    *fl new_line=(*fl)malloc(sizeof(fl));
    i=1;
    
    f->fl =fl;
    *******************************
    fl is recognized in the scope but it losses all values when i am out of the function

    what am i doing wrong?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Well better names would be a help, rather than short identifiers differing only by a single letter.

    Code:
    typedef struct node {
        item *item;
        node *next;
    } node;
    
    typedef struct item {
        int i;
    } item;
    Then
    Code:
    node *makeNewNode ( int i ) {
      node *newNode = malloc(sizeof(*newNode));
      newNode->item = malloc(sizeof(*newNode->item));
      newNode->item->i = i;
      newNode->next = NULL;
      return newNode;
    }
    > what am i doing wrong?
    Hard to say, you didn't really post enough code to say for sure.
    Random 1-line snippets of your thoughts doesn't really work.
    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
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    The code you've posted is full of typos!
    It won't even compile, let alone run.
    There are so many errors it's ridiculous!
    Please don't type ridiculously broken code into the forum.
    Instead, copy and paste your actual code.
    That way we won't waste our time on your stupid typos.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 11
    Last Post: 06-27-2012, 07:05 AM
  2. Replies: 1
    Last Post: 05-12-2011, 01:02 AM
  3. 2 problems: Struct array and pointer + struct
    By v1n1c1u5 in forum C Programming
    Replies: 0
    Last Post: 12-13-2009, 05:38 PM
  4. Replies: 1
    Last Post: 05-05-2004, 06:58 AM
  5. returning a pointer of a struct of a struct array...
    By myrddinb in forum C Programming
    Replies: 1
    Last Post: 04-13-2004, 06:49 PM

Tags for this Thread