Making pascal's triangle with mpz_t's - c

Hey, I'm trying to convert a function I wrote to generate an array of longs that respresents Pascal's triangles into a function that returns an array of mpz_t's. However with the following code:
mpz_t* make_triangle(int rows, int* count) {
//compute triangle size using 1 + 2 + 3 + ... n = n(n + 1) / 2
*count = (rows * (rows + 1)) / 2;
mpz_t* triangle = malloc((*count) * sizeof(mpz_t));
//fill in first two rows
mpz_t one;
mpz_init(one);
mpz_set_si(one, 1);
triangle[0] = one; triangle[1] = one; triangle[2] = one;
int nums_to_fill = 1;
int position = 3;
int last_row_pos;
int r, i;
for(r = 3; r <= rows; r++) {
//left most side
triangle[position] = one;
position++;
//inner numbers
mpz_t new_num;
mpz_init(new_num);
last_row_pos = ((r - 1) * (r - 2)) / 2;
for(i = 0; i < nums_to_fill; i++) {
mpz_add(new_num, triangle[last_row_pos + i], triangle[last_row_pos + i + 1]);
triangle[position] = new_num;
mpz_clear(new_num);
position++;
}
nums_to_fill++;
//right most side
triangle[position] = one;
position++;
}
return triangle;
}
I'm getting errors saying: incompatible types in assignment for all lines where a position in the triangle is being set (i.e.: triangle[position] = one;).
Does anyone know what I might be doing wrong?

mpz_t is define as an array of length 1 of struct __mpz_struct, which prevents assignment. This is done because normal C assignment is a shallow copy and the various gmp numeric types store pointers to arrays of "limbs" that need to be deep copied. You need to use mpz_set or mpz_init_set (or even mpz_init_set_si) to assign MP integers, making sure you initialize the destination before using the former.
Also, you should call mpz_clear at most once for every mpz_init (they're like malloc and free in this regard, and for the same reasons). By calling mpz_init(new_nom) in the outer loop mpz_clear(new_num) in the inner loop, you're introducing a bug which will be evident when you examine the results of make_triangle. However, you don't even need new_num; initialize the next element of triangle and use it as the destination of mpz_add.
mpz_init(triangle[position]);
mpz_add(triangle[position++], triangle[last_row_pos + i], triangle[last_row_pos + i + 1]);
Small numeric optimization: you can update last_row_pos using an addition and subtraction rather than two subtractions, a multiplication and division. See if you can figure out how.

Related

Optimize Radix Sort

For a programming assignment I had to create a radix sort algorithm that worked with floating point numbers in their binary versions. The end goal of the assignment was to sort 100 million floating point numbers in under 2 minutes.
The algorithm itself took me a while to get working but as of now it has been really efficient. I am able to sort the 100 million numbers in about 30 seconds. The important note is that the floats have to be converted to unsigned ints so that bit-wise operations can be applied to them. The code that I used to do that I saw in a video on Quake 3's Fast Inverse Square Root Algorithm. Here is the code that I wrote for the assignment.
void radixsort(float *array, unsigned int length, unsigned int bits) {
double sum = 0;
// Create buckets
float *bucketsA = (float *) malloc(length * sizeof(float));
float *bucketsB = (float *) malloc(length * sizeof(float));
unsigned int aIndex = 0, bIndex = 0;
for (int i = 0; i < bits; i++) {
// Sort array using digit position d as the key.
for (int j = 0; j < length; j++) {
if (i == 0) sum += array[j];
unsigned int conversion = * (unsigned int *) &array[j];
int positionBit = nthBit(conversion, i);
if (positionBit == 0) {
bucketsA[aIndex] = array[j];
aIndex++;
}
else {
bucketsB[bIndex] = array[j];
bIndex++;
}
}
// Combine and move sorted buckets into original array
if(i == bits - 1) {
reverseArray(bucketsB, bIndex);
memcpy(array, bucketsB, (bIndex + 1) * sizeof(float));
memcpy(array + bIndex, bucketsA, (aIndex + 1) * sizeof(float));
}
else {
memcpy(array, bucketsA, (aIndex + 1) * sizeof(float));
memcpy(array + aIndex, bucketsB, (bIndex + 1) * sizeof(float));
}
// Reset the memory of the buckets
memset(&bucketsA[0], 0, sizeof(float) * length);
memset(&bucketsB[0], 0, sizeof(float) * length);
// Reset bucket index
aIndex = bIndex = 0;
}
printf("Total: %f\n", sum);
// Free reserved memory
free(bucketsA);
free(bucketsB);
}
I have two questions relating to the following code:
The first is that when I commented out freeing the reserved memory at the bottom I was expecting a segmentation fault but nothing happened, why is this? I might be a little confused on how memory on the heap and stack works but I thought that if the memory was not freed even though it is local it should cause an error. Freeing the memory actually slowed down the program as well.
The second question is does anyone see any obvious way to make the program run faster? I am already way below the minimum requirement for time and most of my classmates' programs are sorting the 100 million numbers in 1:30+ so I have nothing to worry about but I saw in a post someone managed to get their radix sort to run through 100 million in about 15 seconds. In this implementation I started with LSB so I wonder if starting with MSB will make the program faster but I don't have much time to really test with finals coming up. Thank you for the help.
EDIT: Here is the code for the nthBit and reverseArray
int nthBit(int number, int n) {
return (number >> n) & 1;
}
void reverseArray(float *array, int size) {
for (int i = 0; i < (size / 2); i++) {
float swap = array[size - 1 - i];
array[size - 1 - i] = array[i];
array[i] = swap;
}
}

(Computational fluid dynamics) Problem with arrays. Why is my C program outputting -1.#IND00

I have a problem with a program i'm writing in C that solves the 1D linear convection equation. Basically i have initialized an two arrays. The first array (u0_array) is an array of ones with the arrays elements set equal to two over the interval or 0.5 < x < 1. The second array (usol_array) serves as a temporary array that the result or solution will be stored in.
The problem i am running into is the nested for loop at the end of my code. This loop applies the update equation required to calculate the next point, to each element in the array. When i run my script and try to print the results the output i get is just -1.IND00 for each iteration of the loop. (I am following Matlab style pseudo code which i also have attached below) I'm very new with C so my inexperience shows. I don't know why this is happening. If anyone could suggest a possible fix to this i would be very grateful. I have attached my code so far below with a few comments so you can follow my thought process. I have also attached the Matlab style pseudo code i'm followed.
# include <math.h>
# include <stdlib.h>
# include <stdio.h>
# include <time.h>
int main ( )
{
//eqyation to be solved 1D linear convection -- du/dt + c(du/dx) = 0
//initial conditions u(x,0) = u0(x)
//after discretisation using forward difference time and backward differemce space
//update equation becomes u[i] = u0[i] - c * dt/dx * (u0[i] - u[i - 1]);
int nx = 41; //num of grid points
int dx = 2 / (nx - 1); //magnitude of the spacing between grid points
int nt = 25;//nt is the number of timesteps
double dt = 0.25; //the amount of time each timestep covers
int c = 1; //assume wavespeed
//set up our initial conditions. The initial velocity u_0
//is 2 across the interval of 0.5 <x < 1 and u_0 = 1 everywhere else.
//we will define an array of ones
double* u0_array = (double*)calloc(nx, sizeof(double));
for (int i = 0; i < nx; i++)
{
u0_array[i] = 1;
}
// set u = 2 between 0.5 and 1 as per initial conditions
//note 0.5/dx = 10, 1/dx+1 = 21
for (int i = 10; i < 21; i++)
{
u0_array[i] = 2;
//printf("%f, ", u0_array[i]);
}
//make a temporary array that allows us to store the solution
double* usol_array = (double*)calloc(nx, sizeof(double));
//apply numerical scheme forward difference in
//time an backward difference in space
for (int i = 0; i < nt; i++)
{
//first loop iterates through each time step
usol_array[i] = u0_array[i];
//printf("%f", usol_array[i]);
//MY CODE WORKS FINE AS I WANT UP TO THIS LOOP
//second array iterates through each grid point for that time step and applies
//the update equation
for (int j = 1; j < nx - 1; j++)
{
u0_array[j] = usol_array[j] - c * dt/dx * (usol_array[j] - usol_array[j - 1]);
printf("%f, ", u0_array[j]);
}
}
return EXIT_SUCCESS;
}
For reference also the pseudo code i am following is attached below
1D linear convection pseudo Code (Matlab Style)
Instead of integer division, use FP math.
This avoid the later division by 0 and -1.#IND00
// int dx = 2 / (nx - 1); quotient is 0.
double dx = 2.0 / (nx - 1);
OP's code does not match comment
// u[i] = u0[i] - c * dt/dx * (u0[i] - u[i - 1]
u0_array[j] = usol_array[j] - c * dt/dx * (usol_array[j] - usol_array[j - 1]);
Easier to see if the redundant _array removed.
// v correct?
// u[i] = u0[i] - c * dt/dx * (u0[i] - u[i - 1]
u0[j] = usol[j] - c * dt/dx * (usol[j] - usol[j - 1]);
// ^^^^ Correct?
What you probably want is in matlab terms
for i = 1:nt
usol = u0
u0(2:nx) = usol(2:nx) - c*dt/dx*(usol(2:nx)-usol(1:nx-1))
end%for
This means that you have 2 inner loops over the space dimension, one for each of the two vector operations. These two separate loops have to be explicit in the C code
//apply numerical scheme forward difference in
//time an backward difference in space
for (int i = 0; i < nt; i++) {
//first loop iterates through each time step
for (int j = 0; j < nx; j++) {
usol_array[j] = u0_array[j];
//printf("%f", usol_array[i]);
}
//second loop iterates through each grid point for that time step
//and applies the update equation
for (int j = 1; j < nx; j++)
{
u0_array[j] = usol_array[j] - c * dt/dx * (usol_array[j] - usol_array[j - 1]);
printf("%f, ", u0_array[j]);
}
}

Multiplication of very large numbers using character strings

I'm trying to write a C program which performs multiplication of two numbers without directly using the multiplication operator, and it should take into account numbers which are sufficiently large so that even the usual addition of these two numbers cannot be performed by direct addition.
I was motivated for this when I was trying to (and successfully did) write a C program which performs addition using character strings, I did the following:
#include<stdio.h>
#define N 100000
#include<string.h>
void pushelts(char X[], int n){
int i, j;
for (j = 0; j < n; j++){
for (i = strlen(X); i >= 0; i--){
X[i + 1] = X[i];
}
X[0] = '0';
}
}
int max(int a, int b){
if (a > b){ return a; }
return b;
}
void main(){
char E[N], F[N]; int C[N]; int i, j, a, b, c, d = 0, e;
printf("Enter the first number: ");
gets_s(E);
printf("\nEnter the second number: ");
gets_s(F);
a = strlen(E); b = strlen(F); c = max(a, b);
pushelts(E, c - a); pushelts(F, c - b);
for (i = c - 1; i >= 0; i--){
e = d + E[i] + F[i] - 2*'0';
C[i] = e % 10; d = e / 10;
}
printf("\nThe answer is: ");
for (i = 0; i < c; i++){
printf("%d", C[i]);
}
getchar();
}
It can add any two numbers with "N" digits. Now, how would I use this to perform multiplication of large numbers? First, I wrote a function which performs the multiplication of number, which is to be entered as a string of characters, by a digit n (i.e. 0 <= n <= 9). It's easy to see how such a function is written; I'll call it (*). Now the main purpose is to multiply two numbers (entered as a string of characters) with each other. We might look at the second number with k digits (assuming it's a1a2.....ak) as:
a1a2...ak = a1 x 10^(k - 1) + a2 x 10^(k - 2) + ... + ak-1 x 10 + ak
So the multiplication of the two numbers can be achieved using the solution designed for addition and the function (*).
If the first number is x1x2.....xn and the second one is y1y2....yk, then:
x1x2...xn x y1y2...yk = (x1x2...xn) x y1 x 10^(k-1) + .....
Now the function (*) can multiply (x1x2...xn) with y1 and the multiplication by 10^(k-1) is just adding k-1 zero's next to the number; finally we add all of these k terms with each other to obtain the result. But the difficulty lies in just knowing how many digits each number contains in order to perform the addition each time inside the loop designed for adding them together. I have thought about doing a null array and each time adding to it the obtained result from multiplication of (x1x2....xn) by yi x 10^(i-1), but like I've said I am incapable of precising the required bounds and I don't know how many zeros I should each time add in front of each obtained result in order to add it using the above algorithm to the null array. More difficulty arises when I'll have to do several conversions from char types into int types and conversely. Maybe I'm making this more complicated than it should; I don't know if there's an easier way to do this or if there are tools I'm unaware of. I'm a beginner at programming and I don't know further than the elementary tools.
Does anyone have a solution or an idea or an algorithm to present? Thanks.
There is an algorithm for this which I developed when doing Small Factorials problem on SPOJ.
This algorithm is based on the elementary school multiplication method. In school days we learn multiplication of two numbers by multiplying each digit of the first number with the last digit of the second number. Then multiplying each digit of the first number with second last digit of the second number and so on as follows:
1234
x 56
------------
7404
+6170- // - is denoting the left shift
------------
69104
What actually is happening:
num1 = 1234, num2 = 56, left_shift = 0;
char_array[] = all digits in num1
result_array[]
while(num2)
n = num2%10
num2 /= 10
carry = 0, i = left_shift, j = 0
while(char_array[j])
i. partial_result = char_array[j]*n + carry
ii. partial_result += result_array[i]
iii. result_array[i++] = partial_result%10
iv. carry = partial_result/10
left_shift++
Print the result_array in reverse order.
You should note that the above algorithm work if num1 and num2 do not exceed the range of its data type. If you want more generic program, then you have to read both numbers in char arrays. Logic will be the same. Declare num1 and num2 as char array. See the implementation:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char num1[200], num2[200];
char result_arr[400] = {'\0'};
int left_shift = 0;
fgets(num1, 200, stdin);
fgets(num2, 200, stdin);
size_t n1 = strlen(num1);
size_t n2 = strlen(num2);
for(size_t i = n2-2; i >= 0; i--)
{
int carry = 0, k = left_shift;
for(size_t j = n1-2; j >= 0; j--)
{
int partial_result = (num1[j] - '0')*(num2[i] - '0') + carry;
if(result_arr[k])
partial_result += result_arr[k] - '0';
result_arr[k++] = partial_result%10 + '0';
carry = partial_result/10;
}
if(carry > 0)
result_arr[k] = carry +'0';
left_shift++;
}
//printf("%s\n", result_arr);
size_t len = strlen(result_arr);
for(size_t i = len-1; i >= 0; i-- )
printf("%c", result_arr[i]);
printf("\n");
}
This is not a standard algorithm but I hope this will help.
Bignum arithmetic is hard to implement efficiently. The algorithms are quite hard to understand (and efficient algorithms are better than the naive one you are trying to implement), and you could find several books on them.
I would suggest using an existing Bignum library like GMPLib or use some language providing bignums natively (e.g. Common Lisp with SBCL)
You could re-use your character-string-addition code as follows (using user300234's example of 384 x 56):
Set result="0" /* using your character-string representation */
repeat:
Set N = ones_digit_of_multiplier /* 6 in this case */
for (i = 0; i < N; ++i)
result += multiplicand /* using your addition algorithm */
Append "0" to multiplicand /* multiply it by 10 --> 3840 */
Chop off the bottom digit of multiplier /* divide it by 10 --> 5 */
Repeat if multiplier != 0.

Scaling a bitmap image getting segfault

Sup guys, learning C and working on a C programming assignment where I am to scale a given bitmap image and I have been stuck on this all day. this is my code thus far but I am getting a segfault and can't figure out why. I've been tracing through the code all day and am just stuck. here is my code of the function to scale, any help would be appreciated
int enlarge(PIXEL* original, int rows, int cols, int scale,
PIXEL** new, int* newrows, int* newcols)
{
int ncols, nrows;
ncols = cols * scale;
nrows = rows * scale;
double xratio =(double) rows / nrows;
double yratio =(double) cols / ncols;
int px, py;
int auxw, cnt;
int i, j;
*new = (PIXEL*)malloc(nrows * ncols * sizeof(PIXEL));
for (i = 0; i < nrows; i++){
auxw = 0;
cnt = 0;
int m = i * 3;
for (j = 0; j < ncols; j++){
px = (int)floor( j * xratio);
py = (int)floor( i * yratio);
PIXEL* o1 = original + ((py*rows + px) *3);
PIXEL* n1 = (*new) + m*ncols + j + auxw;
*n1 = *o1;
PIXEL* o2 = original + ((py*rows + px) *3) + 1;
PIXEL* n2 = (*new) + m*ncols + j + 1 + auxw;
*n2 = *o2;
PIXEL* o3 = original + ((py*rows + px) *3) + 2;
PIXEL* n3 = (*new) + m*ncols + j + 2 + auxw;
*n3 = *o3;
auxw += 2;
cnt++;
}
}
return 0;
}
using the GDB, i get the following :
Program received signal SIGSEGV, Segmentation fault.
0x00000000004013ff in enlarge (original=0x7ffff7f1e010, rows=512, cols=512, scale=2, new=0x7fffffffdeb8,
newrows=0x7fffffffdfb0, newcols=0x0) at maind.c:53
53 *n3 = *o3;
however, I can't understand what exactly the problem is
thanks
EDIT:
Working off code our professor provided for us, a PIXEL is defined as such:
typedef struct {
unsigned char r;
unsigned char g;
unsigned char b;
} PIXEL;
From my understanding i have a 2 dimensional array where each element of that array contains a 3 element PIXEL array.
Also, when tracing my code on paper, I added the auxw logic in order to advance down the array. It works somewhat in the same way as multiplying by 3.
Is your array a cols X rows array of PIXEL objects -- or is it actually an cols X rows X 3 array of PIXEL objects where what you call a pixel is actually really a component channel of a pixel? Your code isn't clear. When accessing the original array, you multiply by 3, suggesting an array of 3 channels:
PIXEL* o1 = original + ((py*rows + px) *3);
But when accessing the (*new) array there is no multiplication by 3, instead there's some logic I cannot follow with auxw:
PIXEL* n1 = (*new) + m*ncols + j + auxw;
auxw += 2;
Anyway, assuming that what you call a pixel is actually a channel, and that there are the standard 3 RGB channels in each pixel, you need to allocate 3 times as much memory for your array:
*new = (PIXEL*)malloc(nrows * ncols * 3*sizeof(PIXEL));
Some additional issues:
int* newrows and int* newcols are never initialized. You probably want to initialize them to the values of nrows and ncols
If PIXEL is really a CHANNEL, then rename it to correctly express its meaning.
Rather than copying logic for multidimensional array pointer arithmetic all over the place, protect yourself from indexing off your pixel/channel/whatever arrays by using a function:
#include "assert.h"
PIXEL *get_channel(PIXEL *pixelArray, int nRows, int nCols, int nChannels, int iRow, int iCol, int iChannel)
{
if (iRow < 0 || iRow >= nRows)
{
assert(!(iRow < 0 || iRow >= nRows));
return NULL;
}
if (iCol < 0 || iCol >= nCols)
{
assert(!(iRow < 0 || iRow >= nRows));
return NULL;
}
if (iChannel < 0 || iChannel >= nChannels)
{
assert(!(iChannel < 0 || iChannel >= nChannels));
return NULL;
}
return pixelArray + (iRow * nCols + iCol) * nChannels + iChannel;
}
Later, once your code is fully debugged, if performance is a problem you can replace the function with a macro in release mode:
#define get_channel(pixelArray, nRows, nCols, nChannels, iRow, iCol, iChannel)\
((pixelArray) + ((iRow) * (nCols) + (iCol)) * (nChannels) + (iChannel))
Another reason to use a standard get_channel() function is that your pointer arithmetic is inconsistent:
PIXEL* o1 = original + ((py*rows + px) *3);
PIXEL* n1 = (*new) + m*ncols + j + auxw;
to access the original pixel, you do array + iCol * nRows + iRow, which looks good. But to access the *new array, you do array + iCol * nCols + iRow, which looks wrong. Make a single function to access any pixel array, debug it, and use it.
Update
Given your definition of the PIXEL struct, it is unnecessary for you to be "adding those +1 and +2 values allowed me to reach the second and third element of the PIXEL struct." Since PIXEL is a struct, if you have a pointer to one you access its fields using the -> operator:
PIXEL *p_oldPixel = get_pixel(old, nRowsOld, nColsOld, iRowOld, iColOld);
PIXEL *p_newPixel = get_pixel(*p_new, nRowsNew, nColsNew, iRowNew, iColNew);
p_newPixel->r = p_oldPixel->r;
p_newPixel->g = p_oldPixel->g;
p_newPixel->b = p_oldPixel->b;
Or, in this case you can use the assignment operator to copy the struct:
*p_newPixel = *p_oldPixel;
As for indexing through the PIXEL array, since your pointers are correctly declared as PIXEL *, the C compiler's arithmetic will multiply offsets by the size of the struct.
Also, I'd recommend clarifying your code by using clear and consistent naming conventions:
Use consistent and descriptive names for loop iterators and boundaries. Is i a row or a column? Why use i in one place but py in another? A consistent naming convention helps to ensure you never mix up your rows and columns.
Distinguish pointers from variables or structures by prepending "p_" or appending "_ptr". A naming convention that clearly distinguishes pointers can make instances of pass-by-reference more clear, so (e.g.) you don't forget to initialize output arguments.
Use the same syllable for all variables corresponding to the old and new bitmaps. E.g. if you have arguments named old, nRowsOld and nColsOld you are less likely to accidentally use nColsOld with the new bitmap.
Thus your code becomes:
#include "assert.h"
typedef struct _pixel {
unsigned char r;
unsigned char g;
unsigned char b;
} PIXEL;
PIXEL *get_pixel(PIXEL *pixelArray, int nRows, int nCols, int iRow, int iCol)
{
if (iRow < 0 || iRow >= nRows)
{
assert(!(iRow < 0 || iRow >= nRows));
return NULL;
}
if (iCol < 0 || iCol >= nCols)
{
assert(!(iRow < 0 || iRow >= nRows));
return NULL;
}
return pixelArray + iRow * nCols + iCol;
}
int enlarge(PIXEL* old, int nRowsOld, int nColsOld, int scale,
PIXEL **p_new, int *p_nRowsNew, int *p_nColsNew)
{
int nColsNew = nColsOld * scale;
int nRowsNew = nRowsOld * scale;
double xratio =(double) nRowsOld / nRowsNew;
double yratio =(double) nColsOld / nColsNew;
int iRowNew, iColNew;
*p_new = malloc(nRowsNew * nColsNew * sizeof(PIXEL));
*p_nRowsNew = nRowsNew;
*p_nColsNew = nColsNew;
for (iRowNew = 0; iRowNew < nRowsNew; iRowNew++){
for (iColNew = 0; iColNew < nColsNew; iColNew++){
int iColOld = (int)floor( iColNew * xratio);
int iRowOld = (int)floor( iRowNew * yratio);
PIXEL *p_oldPixel = get_pixel(old, nRowsOld, nColsOld, iRowOld, iColOld);
PIXEL *p_newPixel = get_pixel(*p_new, nRowsNew, nColsNew, iRowNew, iColNew);
*p_newPixel = *p_oldPixel;
}
}
return 0;
}
I haven't tested this code yet, but by using consistent naming conventions one can clearly see what it is doing and why it should work.

returning a multidimensional pointer in c

error lvalue returned as left operand of assignment
What is the error in this program;
int(*matrix)[row][col];
int i = 0;
if(n == 1)
{
for (int i = 0; i < no_matrices; i++)
{
printf("Matrix %d", i + 1);
(matrix + i) = GetMatrixU(row, col); // (error here)
}
}
int* GetMatrixU(int row, int col)
srand(time(NULL));
int(* matrix)[col] = malloc(col*sizeof(int));
for (int i = 0; i < row; i ++)
{
for (int j = 0; j < col; j ++)
{
matrix[i][j] = rand()%100;
}
}
return matrix[];
}
The problem is this line:
(matrix + i) = GetMatrixU(row, col);
This tries to make an assignment. The expression on the right is evaluated; this is the "r-value" ("r" for "right"). Then the result should be assigned to the expression on the left, which is the "l-value" ("l" for "left").
Well, (matrix + i) is not a valid l-value. matrix by itself is a single pointer to a two-dimensional array. In C, you can't just specify a pointer value and assign to it; you must use the * operator to dereference the array, and assign through that.
Here is a short code sample that shows how to dereference a pointer, and then repeats your error.
main()
{
int a[10];
*(a + 1) = 0; // proper use of * to dereference
a + 1 = 0; // will not compile; error is "l-value required"
}
But in C, there is a shortcut way to add to a pointer and then dereference it. It is the use of square brackets and an index value:
a[1] = 0; // index the array
In C, the expressions *(a + i) and a[i] mean exactly the same thing, by definition.
http://en.wikipedia.org/wiki/C_syntax#Accessing_elements
It looks like you are trying to create a random matrix, one row at a time. And you are allocating memory for each row. Your basic matrix declaration should be an array of pointers to rows.
int *matrix[rows];
for (i = 0; i < rows; ++i)
{
// either of these lines will work; pick just one
*(matrix + i) = AllocateRandomRow(cols); // explicit add-and-dereference
matrix[i] = AllocateRandomRow(cols); // simpler: just index array
}
I favor the second, simpler syntax for solving this problem. You are indexing an array; just use the square brackets.
Here is a free online text that describes how to dynamically allocate a matrix.
http://www.eskimo.com/~scs/cclass/int/sx9b.html
Here's an example of simpler case to understand this more complex case:
int b = 4;
int *a = &b; // Allowed and works because a is a pointer to an integer
a+1 = 5; // Not allowed no idea about the type of a+1 and it could be used!!
Why this relates to your problem ?
int(*matrix)[5][5];
printf("%p\n",matrix);
printf("%p\n",matrix+1);
Output
0xb7753000
0xb7753064
Difference between the above pointers is of 6*16 + 4 = 100. This number is nothing but row*col*sizeOf(int) = 5*5*4 = 100
Therefore, what you want to do was accessing the cells in matrix, however what you are actually doing is trying to access a memory that your not allowed to use as in the first simple example.
Example of what you are actually doing vs what you wanted the program to do:
int(*matrix)[5][5];
matrix + 0 => address of matrix
matrix + 1 => address of matrix + 100 bytes (you expected + 4 bytes instead)
matrix + 2 => address of matrix + 200 bytes (you expected + 8 bytes instead)
etc...

Resources