pointer fun

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?

Here's the code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <stdio.h>
#include <time.h>
#include <stdlib.h>


int main() {
  
  srand( time(NULL));
  int ** p[10];
  for ( int i = 0; i < 10; i++) {
     int * j[10];
     p[i] = &j[i];
     for (int j = 0; j < 10; j++) {
       p[i][j] = malloc( sizeof( int ) );
       *p[i][j] =  (rand() % 125 + 1);
     }
  }
  
  
    for ( int i = 0; i < 10; i++) {
     for (int j = 0; j < 10; j++) {
       printf("%d  ", p[i][j]);
       //free(p[i][j]);
       //printf("%d  ", p[i][j]);
     }
  }
  
  return 0;



}
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] = new int[10];
Last edited on
Thanks. Very interesting. An array being a pointer but its index dereferencing it.
Topic archived. No new replies allowed.