Reputation: 780
Just started to learn C language. I have a pointer array int *parr and I need to fill it with random numbers and then do some other things with it. But I even don't understand how to fill it with random numbers. I tried something like this, but it hangs the program:
for(i=0 ; i<R ; i++)
{
for(j=0 ; j<C; j++)
{
*(parr+i*C+j)=rand() % 10;
printf("%d",*(parr+i*C+j));
}
printf("\n");
}
Upvotes: 0
Views: 257
Reputation: 32953
int *parr;
just defines a pointer to a n integer, but there's no storage associated with it. You could either
int parr[sizeofarray];
or
int *parr = calloc (sizeofarray, sizeof(int));
to obtain the right amount of storage.
based on your example sizeofarray should be at least R * C
.
Upvotes: 2
Reputation: 182609
The way you initialize it, you probably have to malloc
memory like this:
parr = malloc(R * C * sizeof(*parr));
Upvotes: 5