Reputation:
I'm very new to C, this is a test program that i'm trying to make work. The purpose is to put the characters from one dynamically generated matrix into another. The code i've got compiles but never finishes running.
When I comment out the loop at the bottom it will do the printf statement fine, but when I uncomment it it just keeps running and doesn't print. I though C worked sequentially? If something in the loop is broken why is it affecting the printf statement?
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main (void)
{
int n,m,i;
char **matrix = (char**) malloc(m * sizeof(char*));
for ( i = 0; i < m; i++ )
{
matrix[i] = (char*) malloc(n * sizeof(char));
}
char **oldMatrix = (char**) malloc(m * sizeof(char*));
for ( i = 0; i < m; i++ )
{
oldMatrix[i] = (char*) malloc(n * sizeof(char));
}
n=1;
m=2;
int indc;
matrix[n][m];
matrix[1][1]='1';
matrix[1][2]='2';
oldMatrix[1][2];
printf("%c %c",matrix[1][1],matrix[1][2]);
int r=0;
for (indc=0; indc<=1; indc++)
{
printf("4");
oldMatrix[r][indc]=matrix[r][indc];
}
}
Upvotes: 0
Views: 3491
Reputation: 11494
Primary rule: assign value before using any variable. In your m, m is not initialised. Some compiler in debug may help you initialise the variables. but most don't.
Upvotes: 0
Reputation: 36487
Multiple problems here:
First problem: You're using both m
and n
before assigning them any valid value (so their initial value is most likely huge).
Second problem: You're running out of bounds:
n=1;
m=2;
matrix[n][m]; // this line doesn't do anything
matrix[1][1]='1';
matrix[1][2]='2';
In C (and C++) array indexes start at 0, so the first element in an array would be 0, the last one would be one below the number of elements (e.g. an array with x
elements will essentially go from array[0]
to array[x-1]
).
If your array has one element (matrix[n]
which resolves to matrix[1]
) you're only able to access matrix[0]
, matrix[1]
will be out of bounds (i.e. undefined behavior; don't do it!).
Third problem: The way you're allocating your pointers you're swapping dimensions: matrix
will have m
elements and every array stored within will have n
elements. Your other code expects the exact opposite.
Upvotes: 3
Reputation: 4666
First, You are doing malloc calls in the main() without assigning values to m and n. Move n=1 and m=2 statements before the malloc calls.
Second, with these values of n and m and definition of matrix[n][m], you cannot access matrix[1][1] and matrix[1][2] -- the maximum index would need to be n-1 and m-1 since C uses zero-based index to access array elements.
Upvotes: 2