pretty much here is a rough outline of what i have done

struct monster
{
  int health;
  int armor;
  monster *nextaddr;
};

int main()
{
  int num;
  monster *pointer;

  printf("how many monsters do u want");
  sscanf(%d, &num);

  pointer = (monster*)malloc(num * sizeof(monster));
  
  //Here i need some kind of LOOP to populate "x" number of monster objects depending in the input the user entered, my problem arises because im not sure how to correctly do this with the pointer i am given....any advice is greatly appreciated!

  return 0;
}

Recommended Answers

All 3 Replies

Here's what I would do in the for loop

pointer[0].health = some_value;
pointer[0].armor = some_value;
pointer[0].nextaddr = &pointer[1];

Instead of using the constants 0,1 for the array indexes, use variables that increment in the for loop. Also make sure you remember that the last node points to nothing(NULL).

thanks so much! im curious as to what would happen if i tried to do pointer[3].health = some_value;

when i only allocated enough space for 3 structures instead of 4? would my program crash? would it still work but overwrite code that might be used or unused??

It really depends on your C implementation but you can say that it's not proper or safe.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.