Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
C Programming- Calling elements in Arrays question.
#4
Something to understand is that putting a negative number in an array is not what makes a program crash.

Code:
#include <stdio.h>
#include <Windows.h>

int main(void)
{
  int data[5] = {0};
  int moredata[5] = {0};

  data[-1] = 20;

  printf("%d\n", moredata[4]);
  system("pause");
  return 0;
}

What do you think happens when you run the above code? Why?

 Answer

[spoiler=Here's why]
data[i] is syntactic sugar for *(data + i). So it would be fetching *(data + sizeof(data)*i)

So, because of how the stack works in assembly, putting -1 in the array indice invades upon a different array.

One of the most powerful ideas of C is "trust the programmer". C doesn't care if you go outside of array bounds. It assumes that you know what the hell you're doing.
[/spoiler]

I would check elsewhere for your bug.
Reply


Messages In This Thread
C Programming- Calling elements in Arrays question. - by Fiel - 2013-04-02, 08:59 PM

Forum Jump:


Users browsing this thread: 1 Guest(s)