I'm trying to learn pointers...
I have a bizarre little program.
First, I need to know why you don't need to dereference arrays.
Second, Why is the last bit of numbers coming out with exceedingly larger numbers then allowed with the rand() function?
Third, any other knowledge about pointers, like when they should be used and maybe some analogies for use of them?
First: int MyArray[10];MyArray is a pointer, MyArray[x] is de-referencing the value at the (pointer + x*sizeof(type));
Second:
Because you haven't initialized the array correctly. You should do it this way:
1 2 3 4 5 6 7 8 9
int** p; // Pointer to a pointer
p = malloc(10 * sizeof(int)); // Array of pointers
for (int i = 0; i < 10; i++)
{
p[i] = malloc(10 * sizeof(int)); // Make p[i] an array of ints with a size 10*sizeof(int)
for (int j = 0; j < 10; j++)
p[i][j] = rand()%125 + 1;
}
Or you could do this:
1 2 3 4 5 6 7
int* p[10]; // An array of 10 pointers.
for (int i = 0; i < 10; i++)
{
p[i] = malloc(10 * sizeof(int)); // Make p[i] an array of ints with a size 10*sizeof(int)
for (int j = 0; j < 10; j++)
p[i][j] = rand()%125 +1;
}
But it's easiest to do this:
1 2 3 4
int p[10][10];
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
p[i][j] = rand()%125 + 1;
Instead of using p[i] = malloc(10*sizeof(int));, you could also use p[i] = newint[10];