Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Dynamically allocating a member of a structure

linked list realloc

  • Please log in to reply
14 replies to this topic

#13 eafkuor

eafkuor

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 214 posts

Posted 20 March 2011 - 03:44 PM

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct line{
	int number;
	char *content;
	struct line *next;
};

int main( int argc, char **argv ){
	struct line *head; // beginning of the linked list
	//struct line *nodeptr; // rider for moving up and down the list
	head = (struct line *) malloc( sizeof( struct line ) );
	(*head).number = 1;
	(*head).content = (char *) malloc( 32 );
	(*head).next = (struct line *) malloc( sizeof( struct line ) );
	strcpy((*head).content, "Hello, World!\n");
	printf( "%s", (*head).content ); // This line works.
	(*head).content = (char *) realloc( (*head).content, 64 );
	strcpy((*head).content, "Hello, World!\n I'm a longer string, over 32 bytes long\n");
	return 0;
}

strcpy is nothing more than a for copying the second array into the first one byte at a time
  • 0

#14 DarkLordCthulhu

DarkLordCthulhu

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 422 posts
  • Location:The bash shell
  • Programming Language:C, JavaScript, Bash, Others
  • Learning:Ruby, Others

Posted 20 March 2011 - 04:08 PM

Thanks for the suggestion. It seems to work. I found realloc() works with fgets() from a file as well.
  • 0
Programming is a journey, not a destination.

#15 eafkuor

eafkuor

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 214 posts

Posted 20 March 2011 - 04:10 PM

glad it works =)
  • 0





Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download