1

Suppose I declare the following

typedef struct{
    int age;
    int weight;
 } Man;

Then I make an array of Man such as

 Man *manArr = malloc(sizeof(Man) * 2); 

My understanding is that I now have two cells each capable of holding a Man type in them..but how am I able to do this then?

  manArr[45] = (Man) {33, 23};

I would have imagined that I would have seg faulted because there only exists two cells but I can printf the values of manArr[45]. What's a good way to for example go through struct arrays, do something to their fields, and move on to the next without "going out of bounds" per say? Thanks

nochillfam
  • 73
  • 1
  • 5

2 Answers2

2

Accessing out-of-bounds is not guaranteed to segfault. It is defined by the C standard as undefined behavior, i.e. anything can happen, including seemingly error-free behavior.

What's a good way to for example go through struct arrays, do something to their fields, and move on to the next without "going out of bounds" per say?

Remember the size of the array.

const size_t manArrSize = 2;
Man *manArr = malloc(sizeof(Man) * manArrSize); 

for (size_t index = 0; index < manArrSize; ++index)
{
    // Access `manArr[index]`.
}
Emil Laine
  • 41,598
  • 9
  • 101
  • 157
1

Going out of bounds of an array causes undefined behaviour. This means that anything could happen. If you're lucky you'll get a segfault, but you may also get cases where the memory location happens to be somewhere you can access.

As for move on to the next without "going out of bounds":

You could either use an extra variable to store the size of the array, or decide on a sentinel value in the array (and allocate one more slot for it) so that if a certain element is equal to the sentinel value, you know it is the end. For example, argv uses NULL as the sentinel value.

user12205
  • 2,684
  • 1
  • 20
  • 40