i need to make a program where i have a vector(triple pointer) of matrixes, all dynamically allocated. Also, in another matrix, i need to keep the dimensions of the matrixes. The problem is that after i input the values for the 2nd matrix, i keep getting this error : Segmentation fault(core dumped). Can anyone help? Im pretty tight on the deadline. Here is the majority of the code :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "function.h"
#define DEFAULT_CAPACITY 1
int main() {
int capacity = DEFAULT_CAPACITY, size = 0, i, j, k;
int **v = (int **)malloc(DEFAULT_CAPACITY * sizeof(int **));
int **dim = alloc_matrix(capacity,2);
char letter;
printf("Citire litera ");
scanf(" %c",&letter);
while(letter!='Q') {
if(letter=='L') {
int n,m;
scanf("%d %d", &n, &m);
int **a = alloc_matrix(n,m);
read_matrix(n, m, a);
if(size >= capacity) {
capacity = capacity * 2;
int ***tmp;
tmp = (int *)realloc(v, capacity * sizeof(int **));
if(!tmp) {
fprintf(stderr, "realloc() failed\n");
free(v);
return -1;
}
v = tmp;
void *pointer;
pointer = realloc(dim, capacity * sizeof(int *));
dim = pointer;
}
dim[size][0] = n;
dim[size][1] = m;
v[size++] = a;
if(size < capacity) {
capacity = size;
int **tmp = (int **)realloc(v, capacity * sizeof(int **));
if(!tmp) {
fprintf(stderr, "realloc() failed\n");
free(v);
return -1;
}
v = tmp;
void *pointer;
pointer = realloc(dim, capacity * sizeof(int *));
dim = pointer;
}
free_matrix(n, a);
}
int **alloc_matrix(int n, int m) {
int *a = (int *)malloc(n * sizeof(int *));
if(!a) {
fprintf(stderr, "malloc() failed\n");
return NULL;
}
for(int i = 0; i < n;i++) {
a[i] = (int *)malloc(m * sizeof(int));
if(!a) {
fprintf(stderr, "malloc() failed\n");
while(--i >= 0) {
free(a[i]);
}
free(a);
return NULL;
}
}
return a;
}
void read_matrix(int n, int m, int **a) {
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
scanf("%d", &a[i][j]);
}
}
}
I guess the problem is with the realloc of the dim matrix. Any thoughts?
Related
I have a problem returning dynamic array pointer with function parameter. I get segfault
#include <stdio.h>
#include <stdlib.h>
void createArray(int *ptr, int n)
{
ptr = malloc(n * sizeof(int));
for(int i = 1; i <= n; ++i)
{
*(ptr + (i - 1)) = i*i;
}
}
int main() {
int *array = NULL;
int n = 5;
createArray(array, n);
for(int i = 0; i < n; ++i)
{
printf("%d", array[i]);
}
return 0;
}
I have to fill my array with i*i, when I is from 1 to n.
I don't get any errors or warnings. Just message about segmentation fault. Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
Memory must be allocate in the calling function, but not in called.
This variant works:
#include <stdio.h>
#include <stdlib.h>
void createArray(int *ptr, int n){
int i;
for(i = 1; i <= n; i++) {
*(ptr + (i - 1)) = i*i;
// fprintf(stdout,"%d %d\n", i, *(ptr + (i -1)));fflush(stdout);
}
}
int main() {
int i, n, *array = NULL;
void *pvc;
n = 5;
array = (int *)malloc(n * sizeof(int));
createArray(array, n);
for(i = 0; i < n; i++) {
fprintf(stdout,"%d %d\n", i, array[i]);fflush(stdout);
}
pvc = (void *)array;
free(pvc);
return 0;
}
You can change pointer through function parameters like this:
void createArray(int **ptr, int n)
{
*ptr = malloc(n * sizeof(int));
for(int i = 1; i <= n; ++i)
{
(*ptr)[i - 1] = i*i;
}
}
int main() {
int *array = NULL;
int n = 5;
createArray(&array, n);
Remember to call function like this: createArray(&array, n);
I got a question where I need to write a function that reads an integer X and an array A of type int (size N) from the keyboard and eliminates all occurrences of X in A.
for example the input is:
5
1 2 3 4 3
3
and it would return:
A : 1 2 3 4 3
New A : 1 2 4
my code so far is
#include <stdio.h>
#include<stdlib.h>
#define DIM 50
int main() {
int *A;
int N, X;
int *P1, *P2;
do{
scanf("%d", &N);
}while(N<0 || N>DIM);
A= (int*)malloc(N*sizeof(int));
for(P1=A; P1<A+N ; P1++)
scanf("%d ", P1);
printf("\n");
scanf("%d",&X);
printf("A : ");
for(P1=A; P1<A+N ; P1++)
printf("%d ", *P1);
printf("\n");
but I don't know how to continue if you could please help
What you need is to write a function that will erase elements equal to the specified value and reallocate the result array.
Here is a demonstration program where such a function is shown in action.
#include <stdio.h>
#include <stdlib.h>
size_t erase_remove( int **a, size_t n, int value )
{
size_t m = 0;
for (int *p = *a, *q = *a; p != *a + n; ++p)
{
if (*p != value)
{
if (q != p) *q = *p;
++q;
++m;
}
}
if (m != n)
{
int *tmp = realloc( *a, m * sizeof( int ) );
if (tmp != NULL)
{
*a = tmp;
}
else
{
m = -1;
}
}
return m;
}
int main( void )
{
size_t n = 5;
int *a = malloc( n * sizeof( int ) );
size_t i = 0;
a[i++] = 1, a[i++] = 2, a[i++] = 3, a[i++] = 4, a[i++] = 3;
int value = 3;
size_t m = erase_remove( &a, n, value );
if (m != -1) n = m;
for (const int *p = a; p != a + n; ++p)
{
printf( "%d ", *p );
}
putchar( '\n' );
free( a );
}
The program output is
1 2 4
If the memory reallocation for the array within the function was not successful the function returns the value (size_t)-1.
The function preserves the order of elements after removing elements equal to the target value.
If to make the function more general that can deal not only with arrays dynamically allocated then it can look very simply.
size_t erase_remove( int *a, size_t n, int value )
{
size_t m = 0;
for (int *p = a, *q = a; p != a + n; ++p)
{
if (*p != value)
{
if (q != p) *q = *p;
++q;
++m;
}
}
return m;
}
In this case the caller of the function should reallocate the result dynamically allocated array (if it is required) based on the returned value m from the function.
#define N_MAX 50
#define N_MIN 0
int main(void) {
int n;
do{
scanf("%d", &n);
}while(N<N_MIN || N>N_MAX);
int *array = (int*) malloc(sizeof(int) * n);
int i; // number of elements in array
for (i = 0; i < n; i++) {
scanf("%d", array + i);
}
int x;
scanf("%d", &x);
//remove x from arr
for (int j = 0; j <= i; j++) {
if (*(array + j) == x) {
*(array + j) = *(array + i); // replace removed value by last value in array
i--; // decremment number of elements in array
}
}
// print
for (int j = 0; j <= i; j++) {
print("%d", *(array + j));
}
free(array)
}
Try this out!
#include <stdio.h>
#include <stdlib.h>
// Required Prototypes
int *get_nums(char *, size_t *);
int *remove_num(int *, size_t *, int);
void display(char *, int *, size_t);
int main(int argc, char *argv[])
{
size_t size = 0;
int *arr = get_nums("Enter numbers (seperated by space): ", &size);
int num;
printf("Enter number to be removed: ");
scanf("%d", &num);
display("Old Array: ", arr, size);
arr = remove_num(arr, &size, num);
display("New Array: ", arr, size);
free(arr);
return 0;
}
int *get_nums(char *label, size_t *size)
{
size_t length = 0;
int *arr = NULL;
printf("%s", label);
int c, num;
do {
scanf("%d", &num);
arr = realloc(arr, (length + 1) * sizeof(int));
arr[length++] = num;
} while ( (c = getchar()) != '\n' && c != EOF);
*size = length;
return arr;
}
int *remove_num(int *arr, size_t *size, int num)
{
// Copy elements to the new array
// Return the new array
size_t new_size = 0;
int *new_arr = NULL;
for (size_t i = 0; i < *size; ++i) {
if (arr[i] != num) {
new_arr = realloc(new_arr, (new_size + 1) * sizeof(int));
new_arr[new_size++] = arr[i];
}
}
*size = new_size;
free(arr);
return new_arr;
}
void display(char *label, int *arr, size_t size)
{
printf("%s", label);
for (size_t i = 0; i < size; ++i)
printf("%d ", arr[i]);
printf("\n");
}
The main idea is you create an array of integers. Then you copy those elements to a new array which you do not want to remove. And finally you display the new array. That's all. Yes, it's that simple. ;-)
Enter numbers (seperated by space): 1 2 3 4 3
Enter number to be removed: 3
Old Array: 1 2 3 4 3
New Array: 1 2 4
As #Ahmed Masud said in comments about too many reallocations, here's my modified answer. Please do note that the code below is little bit complex but far more efficient than my previous one.
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int *a;
size_t length;
size_t capacity;
} Array;
// Required Prototypes
Array *init_Array(void);
void destroy(Array *);
Array *get_nums(char *);
void remove_num(Array *, int);
void display(char *, Array *);
int main(int argc, char *argv[])
{
Array *arr = get_nums("Enter Numbers (seperated by space): ");
int num;
printf("Enter number to be removed: ");
scanf("%d", &num);
display("Old Array: ", arr);
remove_num(arr, num);
display("New Array: ", arr);
destroy(arr);
return 0;
}
Array *init_Array(void)
{
Array *arr = malloc( sizeof(Array) );
arr->capacity = 1;
arr->length = 0;
arr->a = malloc( sizeof(int) );
return arr;
}
Array *get_nums(char *label)
{
printf("%s", label);
Array *arr = init_Array();
int c, num;
do {
scanf("%d", &num);
// check and reallocate
if (arr->length == arr->capacity) {
arr->a = realloc(
arr->a,
(2 * arr->capacity) * sizeof(int)
);
arr->capacity *= 2;
}
arr->a[arr->length++] = num;
} while ((c = getchar()) != '\n' && c != EOF);
return arr;
}
void remove_num(Array *arr, int num)
{
int remv_idx = -1;
int *a = arr->a;
size_t count = 0;
for (size_t i = 0; i < arr->length; ++i) {
if (a[i] == num) count++;
if (a[i] == num && remv_idx == -1)
remv_idx = i;
if (remv_idx != -1 && remv_idx < i && a[i] != num)
a[remv_idx++] = a[i];
}
arr->length -= count;
arr->capacity = arr->length;
arr->a = realloc(a, arr->capacity * sizeof(int));
}
void display(char *label, Array *arr)
{
printf("%s", label);
for (size_t i = 0; i < arr->length; ++i)
printf("%d ", arr->a[i]);
printf("\n");
}
void destroy(Array *arr)
{
free(arr->a);
free(arr);
}
Here I did not consider any new array but removed the elements in place. I'm keeping both of my solution because you might not need the 2nd one if your input space is small. One more thing, since the question did not mention about any reallocations failures so I did not check it in my code.
Here is an approach:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void print_arr(int *arr, size_t size);
size_t remove_by_value(int *arr, size_t len, int value)
{
int count = 0; // maintain how many times we see value
int k;
for(k = 0; k < len ; k++) {
if ( arr[k] == value ) {
while(arr[count+k] == value) {
count++;
} // skip over conscutive values
if ( count + k >= len )
break;
arr[k] = arr[k+count];
arr[k+count] = value;
print_arr(arr, len);
}
}
return len-count;
}
void print_arr(int *arr, size_t size)
{
for(int k = 0; k < size; k++) {
printf("%02d ", arr[k]);
}
printf("---\n");
}
int main()
{
int test_values[] = { 0, 1, 3, 2, 3, 5, 4, 7, 8 };
size_t len = sizeof(test_values)/sizeof(int);
int *arr = malloc(len*sizeof(int));
memcpy(arr, test_values, len*sizeof(int));
print_arr(arr, len);
len = remove_by_value(arr, len, 3);
print_arr(arr, len);
arr = realloc(arr, len);
print_arr(arr, sizeof(int)*len);
return 0;
}
It bubbles the value to be extracted to the end of the array and lops it off.
The nice thing is that it doesn't use any extra memory to do its work.
The second part that is that it is NOT O(n^2) I have to think a bit about the complexity of it (seems bigger than O(n))
However it's a simple solution that keeps the order of the array, removes unneeded values simply.
i've put in the print_arr function at each step of the loop so that you can see what's happening.
Hopefully the code is clear in its purpose, if you have questions please comment and I will further explanation.
Notes
I expressly did not use sizeof(*arr) because i wanted it to be a bit more clear as to what it is. In production code one would use sizeof(*arr) instead of sizeof(int) .... However I would not be able to create a consistent example (e.g. remove_by_value would have to be similarly made generic) so I didn't to keep the example simple to understand.
I tried to allocate a matrix in int main and I have checked the code and after that I wanted to create specific functions for allocation, reading and printing the matrix and I got some errors I didn't know how to correct.
Below is the code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int *aloc_array(int n)
{
int *v =(int *)malloc(n * sizeof(int *));
if(v = NULL){
free(v);
return NULL;
}
return v;
}
int **aloc_matrix(int n, int *v)
{
int **mat = (int **)malloc(n* sizeof(int *));
if (mat = NULL){
free(mat);
return NULL;
}
for (int i =0 ; i < n; i++){
if (mat[i] == NULL) {
for (int j = 0; j < i; j++) {
free(mat[j]);
}
free(mat);
return NULL;
}
scanf("%d", &v[i]);
mat[i] = (int *)malloc(v[i]* sizeof(int));
for (int j = 0; j < v[i]; j++)
scanf("%X", &mat[i][j]);
}
return mat;
}
void print_matrix(int n, int *v, int **mat)
{
for (int i = 0; i < n; ++i){
for ( int j = 0; j < v[i]; j++){
printf("%08X", mat[i][j]);
}
printf("\n");
}
}
int main(void){
int n, *v, **mat;
scanf("%d", &n);
v = aloc_array(n);
mat =aloc_matrix(n, *v);
print_matrix(n, *v, *mat);
return 0;
}
This is an example of error I get.
000.c:56:25: warning: passing argument 3 of ‘print_matric’ makes pointer from integer without a cast [-Wint-conversion]
You should just pass the variables, dont dereference them
print_matrix(n, v, mat);
note , this is wrong
int *v =(int *)malloc(n * sizeof(int *));
should be
int *v =(int *)malloc(n * sizeof(int));
There are a few bugs in your code:
In the following 2 lines you are assigning, not comparing:
if(v = NULL)
if (mat = NULL)
And lets suppose the result of the comparison was TRUE, the value was NULL... you don't have to call free on it!
The following line:
int *v =(int *)malloc(n * sizeof(int *));
Although it might work, should be changed to:
int *v =(int *)malloc(n * sizeof(int));
You don't need to put the * in the last 2 function calls, change them to:
mat =aloc_matrix(n, v);
print_matrix(n, v, mat);
I'm trying to read a Matrix as here:
I've tried it on Cygwin, and MinGW compilers.
#include <stdio.h>
#include <stdlib.h>
typedef struct _Matrix {
int **data;
int m;
int n;
} Matrix;
Matrix *read_matrix(void) {
Matrix *A;
int i, j;
int **ptr;
A = (Matrix *) malloc(sizeof(Matrix));
if(A == NULL) {
return NULL;
}
printf("Enter m : ");
scanf("%d", &A->m);
printf("Enter n : ");
scanf("%d", &A->n);
ptr = (int **) malloc(A->m * A->n * sizeof(int));
/*-- >> A->data = ptr; << --*/
if(A->data == NULL) {
return NULL;
}
printf("\n");
for(i=0; i<A->m; ++i) {
for(j=0; j<A->n; ++j) {
printf("Enter element [%d][%d] : ", i, j);
scanf("%d", &ptr[i][j]);
}
}
A->data = ptr;
return A;
}
int main() {
Matrix *A;
A = read_matrix();
free(A->data); /* A-- A->data is NULL --*/
free(A);
return 0;
}
If I set A->data before reading in values, I get a SEGMENTATION FAULT.
However, the code here does not appear to crash. However A->data returns NULL. What am I missing here?
A single pointer is all that is needed for the allocation being used.
#include <stdio.h>
#include <stdlib.h>
typedef struct _Matrix {
int *data; //single pointer
int m;
int n;
} Matrix;
Matrix *read_matrix(void) {
Matrix *A;
int i, j;
A = malloc(sizeof(Matrix));
if(A == NULL) {
return NULL;
}
printf("Enter m : ");
scanf("%d", &A->m);
printf("Enter n : ");
scanf("%d", &A->n);
A->data = malloc(A->m * A->n * sizeof(int));
if(A->data == NULL) {
return A;
}
printf("\n");
for(i=0; i<A->m; ++i) {
for(j=0; j<A->n; ++j) {
printf("Enter element [%d][%d] : ", i, j);
scanf("%d", &A->data[( j * A->m) + i]);
}
}
return A;
}
int main() {
Matrix *A;
int i;
int j;
A = read_matrix();
if ( A) {
if ( A->data) {
for(i=0; i<A->m; ++i) {
for(j=0; j<A->n; ++j) {
printf("A[%d][%d]= %d\n", i, j, A->data[( j * A->m) + i]);
}
}
free(A->data);
}
free(A);
}
return 0;
}
I have a pointer to a pointer ("paths") and I want to reallocate each pointer (each "path"). But I get a crash. Generally I am trying to find all possible powers of a number, which one can compute for some amount of operations (e.g for two operations we can get power of three and four (one operation for square of a number, then another one either for power of three or four)). I figured out how to do it on paper, now I am trying to implement it in code. Here is my try:
#include <stdio.h>
#include <stdlib.h>
void print_path(const int *path, int path_length);
int main(void)
{
fputs("Enter number of operations? ", stdout);
int operations;
scanf("%i", &operations);
int **paths, *path, npaths, npath;
npaths = npath = 2;
path = (int*)malloc(npath * sizeof(int));
paths = (int**)malloc(npaths * sizeof(path));
int i;
for (i = 0; i < npaths; ++i) // paths initialization
{
int j;
for (j = 0; j < npath; ++j)
paths[i][j] = j+1;
}
for (i = 0; i < npaths; ++i) // prints the paths, all of them are displayed correctly
print_path(paths[i], npath);
for (i = 1; i < operations; ++i)
{
int j;
for (j = 0; j < npaths; ++j) // here I am trying to do it
{
puts("trying to reallocate");
int *ptemp = (int*)realloc(paths[j], (npath + 1) * sizeof(int));
puts("reallocated"); // tried to write paths[j] = (int*)realloc...
paths[j] = ptemp; // then tried to make it with temp pointer
}
puts("memory reallocated");
++npath;
npaths *= npath; // not sure about the end of the loop
paths = (int**)realloc(paths, npaths * sizeof(path));
for (j = 0; j < npaths; ++j)
paths[j][npath-1] = paths[j][npath-2] + paths[j][j];
for (j = 0; j < npaths; ++j)
print_path(paths[j], npath);
puts("\n");
}
int c;
puts("Enter e to continue");
while ((c = getchar()) != 'e');
return 0;
}
void print_path(const int *p, int pl)
{
int i;
for (i = 0; i < pl; ++i)
printf(" A^%i -> ", p[i]);
puts(" over");
}
I am not sure the problem resides with the call to realloc(), rather you are attempting to write to locations for which you have not created space...
Although you create memory for the pointers, no space is created (allocate memory) for the actual storage locations.
Here is an example of a function to allocate memory for a 2D array of int:
int ** Create2D(int **arr, int cols, int rows)
{
int space = cols*rows;
int y;
arr = calloc(space, sizeof(int));
for(y=0;y<cols;y++)
{
arr[y] = calloc(rows, sizeof(int));
}
return arr;
}
void free2DInt(int **arr, int cols)
{
int i;
for(i=0;i<cols; i++)
if(arr[i]) free(arr[i]);
free(arr);
}
Use example:
#include <ansi_c.h>
int main(void)
{
int **array=0, i, j;
array = Create2D(array, 5, 4);
for(i=0;i<5;i++)
for(j=0;j<4;j++)
array[i][j]=i*j; //example values for illustration
free2DInt(array, 5);
return 0;
}
Another point here is that it is rarely a good idea to cast the return of [m][c][re]alloc() functions
EDIT
This illustration shows my run of your code, just as you have presented it:
At the time of error, i==0 & j==0. The pointer at location paths[0][0] is uninitialized.
EDIT 2
To reallocate a 2 dimension array of int, you could use something like:
int ** Realloc2D(int **arr, int cols, int rows)
{
int space = cols*rows;
int y;
arr = realloc(arr, space*sizeof(int));
for(y=0;y<cols;y++)
{
arr[y] = calloc(rows, sizeof(int));
}
return arr;
}
And here is a test function demonstrating how it works:
#include <stdio.h>
#include <stdlib.h>
int ** Create2D(int **arr, int cols, int rows);
void free2DInt(int **arr, int cols);
int ** Realloc2D(int **arr, int cols, int rows);
int main(void)
{
int **paths = {0};
int i, j;
int col = 5;
int row = 8;
paths = Create2D(paths, col, row);
for(i=0;i<5;i++)
{
for(j=0;j<8;j++)
{
paths[i][j]=i*j;
}
}
j=0;
for(i=0;i<5;i++)
{
for(j=0;j<8;j++)
{
printf("%d ", paths[i][j]);
}
printf("\n");
}
//reallocation:
col = 20;
row = 25;
paths = Realloc2D(paths, col, row);
for(i=0;i<20;i++)
{
for(j=0;j<25;j++)
{
paths[i][j]=i*j;
}
}
j=0;
for(i=0;i<20;i++)
{
for(j=0;j<25;j++)
{
printf("%d ", paths[i][j]);
}
printf("\n");
}
free2DInt(paths, col);
getchar();
return 0;
}
The realloc() does not fail. What fails is that you haven't allocated memory for the new pointers between paths[previous_npaths] and paths[new_npaths-1], before writing to these arrays in the loop for (j = 0; j < npaths; ++j).