I am absolutely new to C and I tried to initialize a array in a function.
But it doesn't work, because if I want to print the values in the main method I always get a Segmentation fault.
static void array(int *i)
{
int j = 0;
i = (int *) malloc(5 * sizeof (int));
for (j = 0; j < 5; j++) {
i[j] = j;
}
for (j = 0; j < 5; j++) {
printf("Hello: %d\n", i[j]);
}
}
/* Main entry point */
int main(int argc, char *argv[])
{
int j;
int *i = NULL;
array(i);
for (j = 0; j < 5; j++) {
printf("Hello: %d\n", i[j]);
}
return 0;
}
Would be nice if someone could fix the code and could explain how it works.
static void array(int **i)
{
int j = 0;
*i = malloc(5 * sizeof (int));
for (j = 0; j < 5; j++) {
(*i)[j] = j;
}
for (j = 0; j < 5; j++) {
printf("Hello: %d\n", (*i)[j]);
}
}
/* Main entry point */
int main(int argc, char *argv[])
{
int j;
int *i = NULL;
array(&i);
for (j = 0; j < 5; j++) {
printf("Hello: %d\n", i[j]);
}
return 0;
}
You are passing a pointer by value into array, so what you need to do is pass a pointer to your pointer instead, then set/use that.
As for why you shouldn't cast the result of a malloc, see: Do I cast the result of malloc? and
Specifically, what's dangerous about casting the result of malloc?
In order to allocate memory to a variable from within a function, you must pass a pointer to a pointer as the function argument, dereference the pointer and then allocate the memory.
or in pseudo-code
function(int **i)
{
*i = malloc...
}
int *i = NULL;
function(&i);
This is one of the ways to do it. You could also return the pointer which malloc returns.
And, from the material I've read, it's a good practice to NOT cast the return type of malloc.
Related
I'm getting a warning:
matrixResult' is used uninitialized in this function [-Wuninitialized]
in this function:
int **addMatrices(int **matrixA, int **matrixB, int *rows, int *cols) {
int **matrixResult = initializeMatrix(matrixResult, rows, cols);
for (int i = 0; i < *rows; i++)
for (int j = 0; j < *cols; j++)
matrixResult[i][j] = matrixA[i][j] + matrixB[i][j];
return matrixResult;
}
But its is getting initialized here:
int **initializeMatrix(int **matrix, int *rows, int *cols) {
matrix = (int **)malloc((*rows) * sizeof(int*));
checkNullPointer(matrix);
for(int i = 0; i < *rows; i++) {
matrix[i] = (int *)calloc(*cols, sizeof(int));
}
return matrix;
}
isn't it? I was trying to find an answer, but everyone just says that 2D array needs to get allocated . But I think that it gets in my code. Anyone has a clue what's going on in here?
You have passed the uninitialised pointer, unnecessarily, and used it as a local variable. If you remove that and use a true local variable, like this:
int **initializeMatrix(int *rows, int *cols) {
int **matrix = malloc((*rows) * sizeof(int*));
checkNullPointer(matrix);
for(int i = 0; i < *rows; i++) {
matrix[i] = calloc(*cols, sizeof(int));
}
return matrix;
}
int **addMatrices(int **matrixA, int **matrixB, int *rows, int *cols) {
int **matrixResult = initializeMatrix(rows, cols);
for (int i = 0; i < *rows; i++)
for (int j = 0; j < *cols; j++)
matrixResult[i][j] = matrixA[i][j] + matrixB[i][j];
return matrixResult;
}
then the warning should go away.
Aside: I also removed the unnecessary casts.
I've written a piece of code but I'm not sure about how it works.
I want to create an array of pointers and pass it as argument to a function, like the following:
int main()
{
int *array[10] = {0};
for(int i = 0; i < 3; i++)
{
array[i] = (int *)malloc(3*sizeof(int *));
}
testFunction(array);
for(int i = 0; i < 3; i++)
{
free(array[i]);
}
return 0;
}
void testFunction(int *array[3])
{
//do something
return;
}
What I don't understand is the following. I declare array as an array of pointers, allocate memory to it by using malloc and then proceed to call testFunction. I want to pass the array by reference, and I understand that when I call the function by using testFunction(array), the array decays to a pointer to its first element (which will be a pointer also). But why in the parameters list I have to write (int *array[3]) with * and not just (int array[3])?
A parameter of type * can accept an argument of type [], but not anything in type.
If you write void testFunction(int arg[3]) it's fine, but you won't be able to access array[1] and array[2] and so on, only the first 3 elements of where array[0] points to. Also a comversion is required (call with testFunction((int*)array);.
As a good practice, it's necessary to make the function parametera consistent with what's passed as arguments. So int *array[10] can be passed to f(int **arg) or f(int *arg[]), but neither f(int *arg) nor f(int arg[]).
void testFunction(int **array, int int_arr_size, int size_of_array_of_pointers)
{
for(int j = 0; j < size_of_array_of_pointers; j++)
{
int *arrptr = array[j]; // this pointer only to understand the idea.
for(int i = 0; i < int_arr_size; i++)
{
arrptr[i] = i + 1;
}
}
}
and
int main()
{
int *array[10];
for(int i = 0; i < sizeof(array) / sizeof(int *); i++)
{
array[i] = malloc(3*sizeof(int));
}
testFunction(array, 3, sizeof(array) / sizeof(int *));
for(int i = 0; i < sizeof(array) / sizeof(int *); i++)
{
free(array[i]);
}
return 0;
}
Evering depends on what // do something means in your case.
Let's start from simple : perhaps, you need just array of integers
If your function change only values in array but does not change size, you can pass it as int *array or int array[3].
int *array[3] allows to work only with arrays of size 3, but if you can works with any arrays of int option int *array require additional argument int size:
void testFunction(int *array, int arr_size)
{
int i;
for(i = 0; i < arr_size; i++)
{
array[i] = i + 1;
}
return;
}
Next : if array of pointers are needed
Argument should be int *array[3] or better int **array (pointer to pointer).
Looking at the initialization loop (I changed sizeof(int *) to sizeof(int))
for(int i = 0; i < 3; i++)
{
array[i] = (int *)malloc(3*sizeof(int));
}
I suppose you need 2-dimension array, so you can pass int **array but with sizes of two dimensions or one size for case of square matrix (height equal to width):
void testFunction(int **array, int wSize, int hSize)
{
int row, col;
for(row = 0; row < hSize; row++)
{
for(col = 0; col < wSize; col++)
{
array[row][col] = row * col;
}
}
}
And finally : memory allocation for 2D-array
Consider the following variant of your main:
int main()
{
int **array;
// allocate memory for 3 pointers int*
array = (int *)malloc(3*sizeof(int *));
if(array == NULL)
return 1; // stop the program
// then init these 3 pointers with addreses for 3 int
for(int i = 0; i < 3; i++)
{
array[i] = (int *)malloc(3*sizeof(int));
if(array[i] == NULL) return 1;
}
testFunction(array, 3, 3);
// First, free memory allocated for int
for(int i = 0; i < 3; i++)
{
free(array[i]);
}
// then free memory allocated for pointers
free(array);
return 0;
}
Pay attention, that value returned by malloc should be checked before usage (NULL means memory was not allocated).
For the same reasons check can be added inside function:
void testFunction(int **array, int wSize, int hSize)
{
int row, col;
if(array == NULL) // check here
return;
for(row = 0; row < hSize; row++)
{
if(array[row] == NULL) // and here
return;
for(col = 0; col < wSize; col++)
{
array[row][col] = row * col;
}
}
}
I know that you can return a pointer to the first element of an array in c by doing:
#include <stdlib.h>
#include <stdio.h>
int *my_func(void);
int main(void)
{
int *a;
int i;
a = my_func();
for(i = 0; i < 3; i++)
{
printf("a[%d] = %d\n", i, a[i]);
}
free(a);
return 0;
}
int *my_func(void)
{
int *array;
int i;
array = calloc(3, sizeof(int));
for(i = 0; i < 3; i++)
{
array[i] = i;
}
return array;
}
But if I wanted to return two pointers instead of just one, I tried:
#include <stdlib.h>
#include <stdio.h>
int *my_func(int *);
int main(void)
{
int *a;
int *b;
int i;
a = my_func(b);
for(i = 0; i < 3; i++)
{
printf("a[%d] = %d\n", i, a[i]);
printf("b[%d] = %d\n", i, b[i]);
}
free(a);
free(b);
return 0;
}
int *my_func(int *array2)
{
int *array;
int i;
array = calloc(3, sizeof(int));
array2 = calloc(3, sizeof(int));
for(i = 0; i < 3; i++)
{
array[i] = i;
array2[i] = i;
}
return array;
}
But this seg faults on the printf for b. I ran it through valgrind and it says that there is an invalid read of size 4 at the printf for b, which means I'm doing something screwy with the b pointer. I was just wondering what the best way to "return" a second pointer to an array was in c? I'm asking because I would like to do it this way rather than use a global variable (I'm not opposed to them, as they are useful at times, I just prefer not to use them if possible). The other questions I've seen on this site used statically allocated arrays, but I haven't yet stumbled across a question that was using dynamic allocation. Thanks in advance!
I can think of three (and a half) simple ways to return multiple items of any kind from a C-function. The ways are described below. It looks like a lot of text, but this answer is mostly code, so read on:
Pass in an output argument as you have done, but do it correctly. You have to allocate space for an int * in main() and then pass the pointer to that to my_func.
In main():
a = my_func(&b);
my_func() becomes:
int *my_func(int **array2)
{
int *array;
int i;
array = calloc(3, sizeof(int));
*array2 = calloc(3, sizeof(int));
for(i = 0; i < 3; i++)
{
array[i] = i;
(*array2)[i] = i;
}
return array;
}
Make your function allocate array of two pointers to the int arrays you are trying to allocate. This will require an additional allocation of two int pointers, but may be worth the trouble.
main() then becomes:
int main(void)
{
int **ab;
int i;
ab = my_func(b);
for(i = 0; i < 3; i++)
{
printf("a[%d] = %d\n", i, ab[0][i]);
printf("b[%d] = %d\n", i, ab[1][i]);
}
free(ab[0]);
free(ab[1]);
free(ab);
return 0;
}
my_func() then becomes:
int **my_func(void)
{
int **arrays;
int i, j;
arrays = calloc(2, sizeof(int *));
arrays[0] = calloc(3, sizeof(int));
arrays[1] = calloc(3, sizeof(int));
for(j = 0; j < 2; j++)
{
for(i = 0; i < 3; i++)
{
arrays[j][i] = i;
}
}
return arrays;
}
Return a structure or structure pointer. You will need to define the structure, and decide whether you want to return the structure itself, a newly allocated pointer to it, or pass it in as a pointer and have my_func() fill it in for you.
The structure definition would look something like this:
struct x
{
int *a;
int *b;
}
You would then rephrase your current functions as one of the following three options:
Direct passing of structure (not recommended for general use):
int main(void)
{
struct x ab;
int i;
ab = my_func();
for(i = 0; i < 3; i++)
{
printf("a[%d] = %d\n", i, ab.a[i]);
printf("b[%d] = %d\n", i, ab.b[i]);
}
free(ab.a);
free(ab.b);
return 0;
}
struct x my_func(void)
{
struct x ab;
int i;
ab.a = calloc(3, sizeof(int));
ab.b = calloc(3, sizeof(int));
for(i = 0; i < 3; i++)
{
ab.a[i] = i;
ab.b[i] = i;
}
return ab;
}
Return a pointer to a dynamically allocated structure (this is a pretty good option in general):
int main(void)
{
struct x *ab;
int i;
ab = my_func();
for(i = 0; i < 3; i++)
{
printf("a[%d] = %d\n", i, ab->a[i]);
printf("b[%d] = %d\n", i, ab->b[i]);
}
free(ab->a);
free(ab->b);
free(ab);
return 0;
}
struct x *my_func(void)
{
struct x *ab;
int i;
ab = malloc(sizeof(struct x));
ab->a = calloc(3, sizeof(int));
ab->b = calloc(3, sizeof(int));
for(i = 0; i < 3; i++)
{
ab->a[i] = i;
ab->b[i] = i;
}
return ab;
}
Allocate the structure in main() and fill it in in my_func via a passed-in pointer. This option is often used in a way where my_func would allocate the structure if you pass in a NULL pointer, otherwise it would return whatever you passed in. The version of my_func shown here has no return value for simplicity:
int main(void)
{
struct x ab;
int i;
my_func(&ab);
for(i = 0; i < 3; i++)
{
printf("a[%d] = %d\n", i, ab.a[i]);
printf("b[%d] = %d\n", i, ab.b[i]);
}
free(ab.a);
free(ab.b);
return 0;
}
void my_func(struct x *ab)
{
int i;
ab->a = calloc(3, sizeof(int));
ab->b = calloc(3, sizeof(int));
for(i = 0; i < 3; i++)
{
ab->a[i] = i;
ab->b[i] = i;
}
return;
}
For all the examples shown here, don't forget to update the declaration of my_func at the top of the file, although I am sure any reasonable compiler will remind you if you forget.
Keep in mind also that these are just three options I pulled out of my brain at a moments notice. While they are likely to cover 99% of any use cases you may come up against any time soon, there are (probably lots of) other options out there.
Function parameters are its local variables. Functions deal with copies of values of the supplied arguments.
You can imagine your function definition and its call the following way
a = my_func(b);
int *my_func( /* int *array2 */ )
{
int *array2 = b;
//...
}
So any changes of the local variable array2 inside the function do not influence on the original argument b.
For such a function definition you have to pass the argument by reference that is the function should be declared like
int *my_func( int **array2 );
^^
There are many ways to implement the function. You could define a structure of two pointers as for example
struct Pair
{
int *a;
int *b;
};
and use it as the return type of the function
struct Pair my_func( void );
Another approach is to pass to the function an array of pointers to the original pointers.
The function can look as it is shown in the demonstrative program.
#include <stdio.h>
#include <stdlib.h>
size_t multiple_alloc( int ** a[], size_t n, size_t m )
{
for ( size_t i = 0; i < n; i++ ) *a[i] = NULL;
size_t k = 0;
for ( ; k < n && ( *a[k] = malloc( m * sizeof( int ) ) ) != NULL; k++ )
{
for ( size_t i = 0; i < m; i++ ) ( *a[k] )[i] = i;
}
return k;
}
#define N 2
#define M 3
int main(void)
{
int *a;
int *b;
multiple_alloc( ( int ** [] ) { &a, &b }, N, M );
if ( a )
{
for ( size_t i = 0; i < M; i++ ) printf( "%d ", a[i] );
putchar( '\n' );
}
if ( b )
{
for ( size_t i = 0; i < M; i++ ) printf( "%d ", b[i] );
putchar( '\n' );
}
free( a );
free( b );
return 0;
}
The program output is
0 1 2
0 1 2
#include <stdlib.h>
#include <stdio.h>
int *my_func(int **);
int main(void)
{
int *a;
int *b;
int i;
b=(int *)malloc(sizeof(int));
a = my_func(&b);
for(i = 0; i < 3; i++)
{
printf("a[%d] = %d\n", i, a[i]);
printf("b[%d] = %d\n", i, b[i]);
}
free(a);
free(b);
return 0;
}
int *my_func(int **array2)
{
int *array;
int i;
array = calloc(3, sizeof(int));
*array2 =calloc(3,sizeof(int));
for(i = 0; i < 3; i++)
{
array[i] = i;
*((*array2)+i)=i;//or (*array2)[i]
}
return array;
}
Pass the pointer by reference. Because its the same logic as, to manipulate an integer block you need to pass a pointer to it. Similarly, to manipulate a pointer, you will have to pass a pointer to it(i.e. pointer to pointer).
https://phoxis.org/2012/07/12/get-sorted-index-orderting-of-an-array/
I tried the method here under the section
Using qsort in C
to sort an array and return the indices, changing the array base_arr to be of type double*. However, when I print the arr[idx[i]] to the screen, half of the values have been changed to 0 and have been sorted as if they had always been 0. What could cause this to happen?
double *BASE_ARR;
int main(int argc, char *argv[]) {
int N = par->N;
int K = par->K;
double *ptr;
ptr = (double *) malloc(N*sizeof(ptr));
int *idx;
idx = (int *) malloc(N*sizeof(idx));
// generate the array to be sorted (ptr), in a separate file
for (int i = 0; i < N; i++) {
idx[i] = i;
}
BASE_ARR = ptr;
// sort
qsort(idx, N, sizeof(idx), idxSort);
for (int i = 0; i < N; i++) {
printf("%f\n",ptr[idx[i]]);
}
for (int i = 0; i < N; i++) {
printf("%d\n",idx[i]);
}
for (int i = 0; i < K; i++) {
idx[i] = -1;
}
return 0;
}
static int idxSort (const void *a, const void *b) {
int aa = *((int *)a), bb = *((int *)b);
if (BASE_ARR[aa] < BASE_ARR[bb]) {
return -1;
}
if (BASE_ARR[aa] == BASE_ARR[bb]) {
printf("what");tack
return 0;
}
if (BASE_ARR[aa] > BASE_ARR[bb]) {
return 1;
}
}
qsort(idx, N, sizeof(idx), idxSort);
should be
qsort(idx, N, sizeof(*idx), idxSort);
idx is a pointer. qsort doesn't need to know the size of a pointer; it needs to know the size of the array element.
Same about your malloc calls. You need to use sizeof(*idx) and sizeof(*ptr) in them. By the way, do not cast the result of malloc.
Can someone wiser than I please explain to me why the following code segment faults? There is no problem allocating the memory by reference, but as soon as I try to assign anything or free by reference, segfault occurs.
I'm sure I'm missing some fundamental concept about pointers and passing by reference, hopefully some light can be shed.
#include <stdlib.h>
#include <stdio.h>
void allocateMatrix(float ***);
void fillMatrix(float ***);
void freeMatrix(float **);
int main() {
float **matrix;
allocateMatrix(&matrix); // this function calls and returns OK
fillMatrix(&matrix); // this function will segfault
freeMatrix(matrix); // this function will segfault
exit(0);
}
void allocateMatrix(float ***m) {
int i;
m = malloc(2*sizeof(float*));
for (i = 0; i < 2; i++) {
m[i] = malloc(2*sizeof(float));
}
return;
}
void fillMatrix(float ***m) {
int i,j;
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
(*m)[i][j] = 1.0; // SEGFAULT
}
}
return;
}
void freeMatrix(float **m) {
int i;
for (i = 0; i < 2; i++) {
free(m[i]); // SEGFAULT
}
free(m);
return;
}
One set of problems is here:
void allocateMatrix(float ***m) {
int i;
m = malloc(2*sizeof(float*));
for (i = 0; i < 2; i++) {
m[i] = malloc(2*sizeof(float));
}
return;
}
You need to assign to *m to get the information back to the calling code, and also you will need to allocate to (*m)[i] in the loop.
void allocateMatrix(float ***m)
{
*m = malloc(2*sizeof(float*));
for (int i = 0; i < 2; i++)
(*m)[i] = malloc(2*sizeof(float));
}
There's at least a chance that the other functions are OK. The fillMatrix() is written and invoked correctly, though it could be simplified by losing the third * from the pointer:
void fillMatrix(float **m)
{
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
m[i][j] = 1.0;
}
}
It might be advisable to pass the triple-pointer to freeMatrix() so that you can zero the pointer in the calling function:
void freeMatrix(float ***m)
{
for (int i = 0; i < 2; i++)
free((*m)[i]);
free(*m);
*m = 0;
}
Calling then becomes:
allocateMatrix(&matrix);
fillMatrix(matrix);
freeMatrix(&matrix);
Good use of indirection. Just try to be consistent with format. It improves readability and reduces errors. e.g.
function calls:
allocateMatrix &matrix
fillMatrix &matrix
freeMatrix &matrix
declarations
void allocateMatrix float ***m
void fillMatrix float ***m
void freeMatrix float ***m
handling
(*m)[i] = malloc(2 * sizeof(float))
(*m)[i][j] = 1.0
free (*m)[i]
Returning of pointer from your function is probably the better way to allocate memory:
float **allocateMatrix() {
int i;
float **m;
m = malloc(2*sizeof(float *));
for (i = 0; i < 2; i++) {
m[i] = malloc(2*sizeof(float));
}
return m;
}
int main() {
float **m;
m = allocateMatrix();
/* do other things
fillMatrix(matrix);
freeMatrix(&matrix);
*/
}