All of lore.kernel.org
 help / color / mirror / Atom feed
From: Jad Saklawi <Jad@Saklawi.info>
To: "J." <mailing-lists@xs4all.nl>
Cc: linux-c-programming@vger.kernel.org
Subject: Re: realloc array of structures
Date: Sun, 25 Apr 2004 20:28:48 +0300	[thread overview]
Message-ID: <1082914128.408bf55066a5a@webmail.namezero.com> (raw)

Quoting "J." <mailing-lists@xs4all.nl>:

> Sunday, April 25 18:08:29
> 
> Hello, 
> 
> I am trying to put incomming data into an array of structures. For example
> everytime a new line arrives, grow the array by one, and copy the line
> into the newly allocated mem structure. 
> 
> Unfortunatly I am a bit lost in the pointer world. Could someone give me
> some hints what to what goes wrong in the small example code below ?

Here is a fixed version of your code :
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct node {
  char *str;
};

int main(void) {
  struct node **strarray = NULL;
  int i = 0, count = 0;
  char line[1024];

  while(fgets(line, 1024, stdin) != NULL) {
    /* grow the array with one element */
    strarray = (struct node **)realloc(strarray, (count + 1) * sizeof(struct
node *));
    strarray[count] = (struct node *)malloc(sizeof(struct node));
    /* copy the line to member str of the new element (structure) */
    strarray[count]->str =  strdup(line);
    count++;
  }

  for(i = 0; i < count; i++)
    printf("[%d].str: %s", i, strarray[i]->str);

  return 0;
}

  You needed to allocate memory for each struct, and you should use -> when
using struct pointers instead of .

Greets,
Jad Saklawi

             reply	other threads:[~2004-04-25 17:28 UTC|newest]

Thread overview: 2+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2004-04-25 17:28 Jad Saklawi [this message]
  -- strict thread matches above, loose matches on Subject: below --
2004-04-25 16:16 realloc array of structures J.

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=1082914128.408bf55066a5a@webmail.namezero.com \
    --to=jad@saklawi.info \
    --cc=linux-c-programming@vger.kernel.org \
    --cc=mailing-lists@xs4all.nl \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.