print 2D matrix in C - c

I'm trying to create and print a matrix, but I'm getting segmentation fault.
int** init_dynamic_matrix (int l, int c);
void print_dynamic_matrix (int** ppints, int l, int c);
int main ()
{
int** ppints = NULL;
int l = 6, c = 3;
ppints = init_dynamic_matrix (l, c);
print_dynamic_matrix (ppints, l, c);
return 0;
}
int** init_dynamic_matrix (int l, int c)
{
int i = 0, j = 0;
int** ppaux = NULL;
ppaux = (int**) malloc (l * (sizeof (int*)));
for (i = 0; i < l; i++)
{
*(ppaux + i) = (int*) malloc (c * (sizeof (int)));
for (j = 0; j < c; j++)
{
ppaux[l][c] = 0;
}
}
return ppaux;
}
void print_dynamic_matrix (int** ppints, int l, int c)
{
int i = 0, j = 0;
for (i = 0; i < l; i++)
{
for (j = 0; j < c; j++)
{
printf ("%d", ppints[l][c]);
}
printf("\n");
}
}

for (j = 0; j < c; j++)
{
ppaux[l][c] = 0;
}
Here's the error: in the first iteration of the outer for loop you will execute this , but ppaux[l] is not yet initialized, so you get segmentation fault.
You probably meant something like:
for (j = 0; j < c; j++)
{
ppaux[i][j] = 0;
}
Because you just created the i-th row of your matrix and you want to se it to 0

Related

I want to show elements of a matrix that appear only once

I got this but it I can't seem to make it work, tried everything I could think of.
#include <stdio.h>
#include <stdlib.h>
void alocare_vector(int *v, int nr, int elem)
{
int *v1;
if ((v1 = realloc(v, nr * sizeof(int))) == NULL)
{
printf("Memorie insuficienta");
free(v);
exit(EXIT_FAILURE);
}
v = v1;
v[nr - 1] = elem;
}
int main()
{
int a[100][100];
int n, *v = NULL, i, j, k, l, ok = 0, nr = 0;
printf("Number de elements n:");
scanf("%d", &n);
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
scanf("%d", &a[i][j]);
for (k = 0; k < n; k++)
{
for (l = 0; l < n; l++)
{
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
if (a[k][l] == a[i][j] && (k != i && l != j))
ok = 1;
if (ok == 0)
{
nr++;
alocare_vector(v, nr, a[k][l]);
}
ok = 0;
}
}
if (nr > 0)
{
printf("Elements:");
for (i = 0; i < nr; i++)
{
printf("%d ", v[i]);
}
}
free(v);
}
Basically, I need to create a matrix, ans print the elements that appear only once using an array with dynamic memory allocation.
one simple fix is to declare the "int * v" as a global variable and modify the function as alocare_vector(int nr, int elem)
now using a hash table you can store the numbers in the array, below is the your implementation just a bit modified.
#include <stdio.h>
#include <stdlib.h>
int hash[1000]={0};
int * v=NULL;
void alocare_vector(int nr, int elem)
{
int *v1;
if ((v1 = (int*)realloc(v, nr * sizeof(int))) == NULL)
{
printf("Memorie insuficienta");
free(v);
exit(EXIT_FAILURE);
}
v = v1;
v[nr - 1] = elem;
}
int main()
{
int a[100][100];
int n, i, j, nr = 0;
printf("Number de elements n:");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
scanf("%d", &a[i][j]);
++hash[a[i][j]];
}
}
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if(hash[a[i][j]]==1)
{
nr++;
alocare_vector(nr, a[i][j]);
}
}
}
if (nr > 0)
{
printf("Elements:");
for (i = 0; i < nr; i++)
{
printf("%d ", v[i]);
}
}
free(v);
}
When calling a your funtion you pass a copy of the pointer. Therfore any modifications to this local copy of the pointer will not affect the copy in main. Therfore you need a refrence or pointer to the pointer in main.
void alocare_vector(int **v, int nr, int elem)
{
...
*v = v1;
}
Here you have brut force example how to generate array of distinct elements of the 2D array:
typedef struct
{
size_t length;
int data[];
}data_t;
data_t *add_element(data_t *arr, int element)
{
size_t newsize = arr ? arr -> length : 0;
arr = realloc(arr, newsize * sizeof(arr -> data[0]) + sizeof(*arr));
if(arr)
{
arr -> length = newsize;
arr -> data[newsize - 1] = element;
}
return arr;
}
int isPresent(size_t rows, size_t cols, size_t vrow, size_t vcol, int (*array)[cols])
{
int val = array[vrow][vcol];
for(size_t row = 0; row < rows; row++)
for(size_t col = 0; col < cols; col++)
{
if(vcol == col && vrow == row) continue;
if(array[row][col] == val)
{
return 1;
}
}
return 0;
}
data_t *distinctElements(size_t rows, size_t cols, int (*array)[cols])
{
data_t *dist = NULL;
for(size_t row = 0; row < rows; row++)
{
for(size_t col = 0; col < cols; col++)
{
if(!isPresent(rows, cols, row, col, array))
{
data_t *tmp = add_element(dist, array[row][col]);
if(tmp) dist = tmp;
else { /* error handling */}
}
}
}
return dist;
}

Return an Array from a function C: Subscripted value is not an array, pointer, or vector

I need to return the value of the matrix, but I am gettin this error
Subscripted value is not an array, pointer, or vector
in:
qk_output[m][o] = 0;
and
qk_output[m][o] += queries[m][n] * keys[n][o];
Could anyone help me? Thanks!
int* multmm(int queries[M][N], int keys[N][O]) {
// Matrix Multiplication
int* qk_output = (int*)malloc(sizeof(int) *M*N);
for (int m = 0; m < M; m++) {
for (int o = 0; o < O; o ++) {
qk_output[m][o] = 0;
for (int n = 0; n < N; n++) {
qk_output[m][o] += queries[m][n] * keys[n][o];
}
}
}
return qk_output;
}
To return a 2D array from a function, you can do
#define N 4
#define M 3
int (*foo(void ))[N]
{
int (*p)[N] = malloc(M * sizeof *p);
for (int i = 0; i < M; ++i)
{
for (int j = 0; j < N; ++j)
{
p[i][j] = i + j;
}
}
return p;
}
int main (void){
int (*mat)[N] = foo();
for (int i = 0; i < M; ++i)
{
for (int j = 0; j < N; ++j)
{
printf("%d ", mat[i][j]);
}
puts("");
}
free(mat);
return 0;
}
int* qk_output = (int*)malloc(sizeof(int) *M*N);
qk_output is a pointer to an int
the compiler knows how to access qk_output[n] but doesn't know how to access qk_output[m][n], you need to switch to:
int (*qk_output)[N] = malloc(sizeof(*qk_output) * M); // Don't cast malloc
that is, a pointer to an array of N ints
Now the compiler has enough information to access qk_output[m][n]
For the return question: you can use void *multmm(...) or int (*multmm(...))[N], the second one gives more information to the compiler so it is less error prone.
Something like:
int (*multmm(int queries[M][N], int keys[N][O]))[N]
{
int (*qk_output)[N] = malloc(sizeof(*qk_output) * M);
...
return qk_output;
}
int main(void)
{
int (*arr2D)[N] = multmm(...);
...
}

Pointers exit code 6

Well i m struggling with the pointers, why doesn t work the function biggest in the end (yes of that s dummy function)? (exit code 6)
Ty for help
code:
int search(int const a[], int n, int key) {
for (int *i = a; i < a + n; i++) {
if ( key == *i ) return 1;
}
return 0;
}
void print_row(int const a[], int n, int row) {
for (int *i = a + n * row; i < a + n * (row + 1); i++) {
printf("%d ", *i);
}
printf("\n");
}
void biggest(double x, long *int_part, double *frac_part) {
*int_part = (long) x;
*frac_part = x - *int_part;
}
main () {
int tempretures[7][24];
for (int *i = &tempretures[0][0]; i < &tempretures[7][24]; i++) {
static int j = 1;
*i = j;
j+=2;
}
tempretures[6][5] = 32;
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 24; j++) {
printf("%d ", tempretures[i][j]);
}
printf("\n");
}
printf("Is it: %d\n", search(tempretures, 7*24, 32));
for (int i = 0; i < 7; i++) {
print_row(tempretures, 24, i);
}
long a = 0; double b = 0;
biggest(5.67, &a, &b);
printf("%li", a);
}
for (int *i = &tempretures[0][0]; i < &tempretures[7][24]; i++) {
static int j = 1;
*i = j;
j+=2;
}
This runs way past the end of the array, stopping only when it hits every element of row number 7, but there is no row number 7.

Why am I getting segmentation fault [139]?

The title is pretty clear I think.
I am trying to create a program that calculates a 3x3 linear system using determinants, but I am getting a segmentation fault. Here is the code:
#include<stdio.h>
int determinant(int n, int m, int det[m][n])
{
int res;
res = det[0][0]*det[1][1] - det[0][1]*det[1][0];
return res;
}
int main(void)
{
int arr[3][4], det[2][2], i, j, D; //Dx1, Dx2, Dx3
for(i = 0; i < 3; i++)
{
printf("Eisagete tous suntelestes ths %dhs eksisoshs.", i+1);
scanf("%d %d %d %d", &arr[i][0], &arr[i][1], &arr[i][2], &arr[i][3]);
}
for(i = 0; i < 2; i++)
{
for(j = 0; j < 2; i++)
{
det[i][j] = arr[i+1][j+1];
}
}
D = arr[0][0]*determinant(2, 2, det);
for(i = 0; i < 2; i++)
{
for(j = 0; j < 2; i++)
{
det[i][j] = arr[i+1][j+((j == 1) ? 1 : 0)];
}
}
D -= arr[0][1]*determinant(2, 2, det);
for(i = 0; i < 2; i++)
{
for(j = 0; j < 2; i++)
{
det[i][j] = arr[i+1][j];
}
}
D += arr[0][2]*determinant(2, 2, det);
printf("%d\n", D);
}
I am getting the error right after completing the first for loop in main.
In the block:
for(i = 0; i < 2; i++)
{
for(j = 0; j < 2; i++)
{
det[i][j] = arr[i+1][j+1];
}
}
You increment i in both loops, and adding 1 more to it while reading from the array. So at arr[i+1] you are reading to far.
A segmentation fault basically means you are trying to read something you don't have access to.
You shoud never do what you're doing by passing static array sizes m and n as function argument:
int determinant(int n, int m, int det[m][n])
Check https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html for info

Segmentation fault in matrix multiplication using multiple threads

#include <stdio.h>
#include <pthread.h>
int arr[1000][1000];
int brr[1000][1000];
int h;
int f;
void *BMM(void *arg)
{
int* neo = (int*) arg;
int ne = *neo;
int sum = 0;
for(int i = 0; i < n; ++i)
{
sum += arr[x][i]*brr[x][f];
++f;
}
printf("%d\n", sum);
crr[x][h] = sum;
pthread_exit(NULL);
}
int main()
{
pthread_t* ar = malloc(3*sizeof(*ar));
printf("Enter the value of m and n\n");
scanf("%d %d",&m,&n);
for(int i = 0; i < m; ++i)
{
for(int j = 0; j < n; ++j)
{
scanf("%d",&arr[i][j]);
}
}
printf("Enter the value of p and q\n");
scanf("%d %d",&p,&q);
if(p != n)
{
printf("The matrix multiplication is not possible\n");
return 0;
}
int* id;
id = (int *)malloc(4*sizeof(int));
for(int i = 0; i < p; ++i)
{
for(int j = 0; j < q; ++j)
{
scanf("%d",&brr[i][j]);
}
}
for(x = 0; x < m; ++x)
{
for(z = 0; z < q; z+=4)
{
f = z;
h = z;
for(int k = 0; k < 3; ++k)
{
pthread_create(&ar[k],NULL,BMM,NULL);
}
for(int k = 0; k < 3; ++k)
{
pthread_join(ar[k],NULL);
}
}
}
for (int i = 0; i < m; ++i)
{
for(int j = 0; j < q; ++j)
{
printf("%d ",crr[i][j]);
}
printf("\n");
}
}
The above program is supposed to multiply two matrix by multiplying row one of matrix by all the columns of other matrix using 3 threads and then row two by all the other columns and so on and then store the respective values int another matrix but it is giving segmentation fault. Where am I going wrong?
I think your problem is here:
pthread_create(&ar[k],NULL,BMM,NULL);
^^^^
void *arg is NULL
and then:
void *BMM(void *arg)
{
int* neo = (int*) arg;
int ne = *neo; // Dereference NULL --> segmentation fault
Further this looks strange:
void *BMM(void *arg)
{
int* neo = (int*) arg;
int ne = *neo; // ne is never used !!
int sum = 0;
for(int i = 0; i < n; ++i) // Where does n come from ?
Perhaps it should be n instead of ne?
If n, x, f and h are global variables you are into trouble as all threads will work on the same variables. That would be real bad. Each thread needs it own variables.
BTW:
Always check the value returned by scanf - something like:
if (scanf("%d %d",&m,&n) != 2)
{
// Add error handling here
}
and
if (scanf("%d",&arr[i][j]) != 1)
{
// Add error handling here
}

Resources