newbie programmer
newbie programmer

Reputation: 21

Explaining pointer array

I'm working on a linking program, consisting of two files. The function createArray() creates an array of some length, which stores random numbers between 0 and 3. It's part of the second file, which gets linked with the first file to create a big program when it's compiled. I have all the declarations from the first file, including the extensions. Anyway, I compile and run the program, but I get a Segmentation Fault error, which I'm assuming it comes down to the line that actually puts the random number into the array.

int length;
int* intArray;
int maxRandVal;

void createArray(){
  length = 16;     
  maxRandVal = 3;  
  intArray[length];
  int i = 0;
  for (i; i < length; i++){
    int r = rand() % (maxRandVal+1);
    intArray[i] = r;
  }
}

I believe my error is that I'm trying to place an integer into a pointer array - something that I still don't understand how it works. How could I insert my random number into a pointer array?

Upvotes: 0

Views: 71

Answers (2)

Prabhu
Prabhu

Reputation: 3541

Where is the intArray pointing to? Allocate memory using malloc for length 16.

intArray = malloc(sizeof(int)*length);

And what are you trying to achive by this:?

intArray[length];

Upvotes: 0

GoldRoger
GoldRoger

Reputation: 1263

Allocate memory for it first using malloc.

intArray = malloc(sizeof(int)*length);

The way you have done does not work. intArray[length]

Dont forget to free that memory once you are done with it .

Upvotes: 1

Related Questions