I am passing a pointer to function and I want to initialze the array of structures in called function and want to use that array main function. But I was unable to get it in main function.
Here is my code:
typedef struct _testStruct
{
int a;
int b;
} testStruct;
void allocate(testStruct** t)
{
int nCount = 0;
int i = 0;
printf("allocate 1\n");
t = (testStruct**)malloc(10 * sizeof(testStruct));
for(i = 0; i < 10; i++)
{
t[i] = (testStruct *) malloc( 10 * sizeof(testStruct));
}
for(nCount = 0 ; nCount < 10; nCount++)
{
t[nCount]->a = nCount;
t[nCount]->b = nCount + 1;
printf( "A === %d\n", t[nCount]->a);
}
}
int main()
{
int nCount = 0;
testStruct * test = NULL;
int n = 0;
allocate(&test);
for(nCount = 0 ; nCount < 10; nCount++ )
{
if (test == NULL)
{
printf( "Not Allocated\n");
exit(0);
}
//printf("a = %d\n",test[nCount]->a);
/*printf("a = %d\n",test->a);
printf("b = %d\n",test->b); */
}
return 0;
}
Please note I have to pass double pointer to function as it is required.
Thank you for helping.
#include <stdio.h>
#include <stdlib.h>
typedef struct _testStruct
{
int a;
int b;
} testStruct;
void allocate(testStruct** t)
{
int nCount = 0;
printf("allocate 1\n");
testStruct *newT = (testStruct*)malloc(10 * sizeof(testStruct));
for(nCount = 0 ; nCount < 10; nCount++)
{
newT[nCount].a = nCount;
newT[nCount].b = nCount + 1;
printf( "A === %d\n", newT[nCount].a);
}
*t = newT;
}
int main()
{
int nCount = 0;
testStruct * test = NULL;
allocate(&test);
for(nCount = 0 ; nCount < 10; nCount++ )
{
printf("a = %d\n",test[nCount].a);
printf("a = %d\n",test[nCount].b);
}
return 0;
}
Should work.
t = (testStruct**)malloc(10 * sizeof(testStruct));
is assigning to t, not test. Perhaps you want
*t = (testStruct*)malloc(10 * sizeof(testStruct));
instead? I'm not sure, I tend to get lost when so many pointers are around. Anyway, you don't seem to be assigning anything into the pointer you pass to your function.
You say you want to create an array of structures, but your allocate function creates a data structure more like two-dimensional array. In addition, you don't return that structure back to the caller in any way that makes sense. I think you have come confusion about pointers, malloc() and all of the indirection you're doing. Check out #Ed Heal's answer for a corrected program.
Related
In a this code,
#include <stdio.h>
#include <stdlib.h>
typedef struct test
{
int i;
double data;
} test;
void add(ar) struct test *ar;
{
int num = 10;
// *ar = malloc(num * sizeof(struct test)); // Adding this
for (int i = 0; i < num; i++)
{
ar[i].i = i;
ar[i].data = i * i;
}
}
int main(void)
{
test ar[10]; // Removing this
add(&ar);
for (int i = 0; i < 10; i++)
{
printf("%d %f\n", ar[i].i, ar[i].data);
}
return 0;
}
How do we define the struct in main but allocate the memory in the function?
I want to set the number (num) inside the function add, as it is not yet known in main.
There are two values you have to pass back from add() to main(), num and the malloc()ed array itself. As you can return only one value, there are two positilities:
a) return num and have a test ** parameter to pass back the array
int add( struct test **ar )
{
int num = 10;
*ar = malloc( num * sizeof **ar );
// initialize everything, you have to replace ar[i] by (*ar)[i]
return num;
}
call it
struct test *ar;
int num = add( &ar );
b) return the array and have a int * parameter to pass back num
struct test *add( int *num )
{
*num = 10;
struct test *ar = malloc( *num * sizeof *ar );
// initialize everything as you do now
return ar;
}
call it
int num;
struct test *ar = add( &num );
As #Bodo mentioned, either way, you have to call free( ar ); in main() when you don't need ar anymore. You could call it directly or think about having a cleanup function like free_test( struct test *ar, int num ); that does the job. Such a function is especially useful if you have more malloc()s to allocate memory for the single struct elements (eg. if they contained char * elements to store strings).
use the argument(s) to pass argument(s)
use the return value to return stuff to the caller
#include <stdio.h>
#include <stdlib.h>
struct test
{
int i;
double data;
} ;
struct test *test_create(unsigned ntest)
{
struct test *pp;
unsigned idx;
pp = malloc(sizeof *pp * ntest);
for (idx = 0; idx < ntest; idx++)
{
pp[idx].i = idx;
pp[idx].data = idx * idx;
}
return pp;
}
int main(void)
{
struct test *ptr;
ptr = test_create(10);
for (int i = 0; i < 10; i++)
{
printf("%d %f\n", ptr[i].i, ptr[i].data);
}
return 0;
}
Update: if you want to return more than a single item, you could put the items together in a struct:
#include <stdio.h>
#include <stdlib.h>
struct dope {
unsigned size;
struct {
int i;
double data;
} *array;
} ;
struct dope *dope_create(void)
{
struct dope *pp;
unsigned omg =10;
pp = malloc(sizeof *pp );
pp->array = malloc(sizeof *pp->array * omg);
pp->size = omg;
for (omg = 0; omg < pp->size; omg++)
{
pp->array[omg].i = omg;
pp->array[omg].data = omg * omg;
}
return pp;
}
int main(void)
{
struct dope *ptr;
ptr = dope_create();
for (int iii = 0; iii < ptr->size; iii++)
{
printf("%d %f\n", ptr->array[iii].i, ptr->array[iii].data);
}
return 0;
}
You have already good answers as alternatives. Anyway I will show you code for 2 common ways of writing this.
As I see in your code, the factory function will determine the actual number of structs test to allocate. I will in the example:
generate a random number of structs, using rand() since it makes no difference here
fill them in like (1,1.01), (2,2.02) ... just to have a known value for testing
show the structs' contents on screen
free() them at exit
assume that can also be 0 structures created
1: use a NULL-terminated sequence of pointers
As it is used with success in all C strings :) we can use it here. As in strings (C strings), you need to search for the terminator in order to get the array size (Of course you can set the first pointer apart for the size, Pascal-like). It can or can not be of importance to know before-hand the # of structs.
Test** add_vector()
{
// returns a null terminated array of pointers
// to 'Test', pointing to actual instances of
// 'Test', allocated and numbered with 'i' starting
// at 1 and 'data' starting at 1.01
int num = rand() % 10; // 0 to 9 Test
fprintf(stderr,
"add_vector(): creating %d structs\n", num);
// at least one pointer, the terminating one
Test** ar = (Test**)malloc((1 + num) * sizeof(Test*));
int ix = 0;
for (ix = 0; ix < num; ix += 1)
{
ar[ix] = (Test*)malloc(sizeof(Test));
// sets up ar[i] to a known value
ar[ix]->i = 1 + ix;
ar[ix]->data = 1 + ix + (1 + ix) / 100.;
}; // for()
ar[ix] = NULL; // the terminator one, as in strings
return ar;
}
To use it you just call
Test** vector = add_vector();
as you see in the example below. A single pointer is returned. No need for arguments. If the number of structs is zero a single pointer is returned, like it would be with an empty string.
The # of structs is defined inside the function, and all structs instances are allocated and numbered before returning to caller.
2: return a pointer to a struct
typedef struct
{
int i;
double data;
} Test;
typedef struct
{
unsigned size;
Test* test;
} V_Test;
V_Test* add_struct();
The allocation function returns a pointer to a V_Test struct, that contains an array of Test strucs and a size elements, an in main() for every C program
int main(in argc, char** argv)
Here is the code:
V_Test* add_struct()
{
// returns a vector of structs inside V_Test,
// with known 'size', like in main( int,char**)
// The structs are initialized with 'i' starting
// at 1 and 'data' starting at 1.01
unsigned num = rand() % 10; // 0 to 9 Test
fprintf(stderr, "add_struct(): creating %d structs\n", num);
V_Test* v = (V_Test*) malloc(sizeof(V_Test));
v->size = num;
if (num == 0)
{
v->test = NULL;
return v;
};
v->test = (Test*)malloc(num * sizeof(Test));
for (unsigned ix = 0; ix < num; ix += 1)
{
v->test[ix].i = 1 + ix;
v->test[ix].data = 1 + ix + (1 + ix) / 100.;
}; // for()
return v;
}
To used it you just call
V_Test* vector = add_struct();
And here also there are no arguments. A new V_Test is allocated and returned.
Also here the # of structs is defined inside the function, and all structs instances are allocated and numbered before returning to caller.
In the code you will see a way of use both functions, create the structs, fill them in, display the contents and release the allocated memory.
Example output
add_vector(): creating 9 structs
# 1: [1, 1.01]
# 2: [2, 2.02]
# 3: [3, 3.03]
# 4: [4, 4.04]
# 5: [5, 5.05]
# 6: [6, 6.06]
# 7: [7, 7.07]
# 8: [8, 8.08]
# 9: [9, 9.09]
9 records were created
9 records were free()'d
add_struct(): creating 4 structs
# 1: [1, 1.01]
# 2: [2, 2.02]
# 3: [3, 3.03]
# 4: [4, 4.04]
4 records were created
4 records were free()'d
C Code
I compiled just once under MSVC.
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int i;
double data;
} Test;
typedef struct
{
unsigned size;
Test* test;
} V_Test;
V_Test* add_struct();
Test** add_vector();
void as_vector_of_pointers();
void as_struct_of_struct();
int main(void)
{
srand(210728);
as_vector_of_pointers();
as_struct_of_struct();
return 0;
}
Test** add_vector()
{
// returns a null terminated array of pointers
// to test
int num = rand() % 10; // 0 to 9 Test
fprintf(stderr,
"add_vector(): creating %d structs\n", num);
// at least one pointer, the terminating one
Test** ar = (Test**)malloc((1 + num) * sizeof(Test*));
int ix = 0;
for (ix = 0; ix < num; ix += 1)
{
ar[ix] = (Test*)malloc(sizeof(Test));
// sets up ar[i] to a known value
ar[ix]->i = 1 + ix;
ar[ix]->data = 1 + ix + (1 + ix) / 100.;
}; // for()
ar[ix] = NULL; // the terminator one, as in strings
return ar;
}
V_Test* add_struct()
{
// returns a vector of structs inside V_Test,
// with known 'size', like in
// main( int,char**)
unsigned num = rand() % 10; // 0 to 9 Test
fprintf(stderr, "add_struct(): creating %d structs\n", num);
V_Test* v = (V_Test*) malloc(sizeof(V_Test));
v->size = num;
if (num == 0)
{
v->test = NULL;
return v;
};
v->test = (Test*)malloc(num * sizeof(Test));
for (unsigned ix = 0; ix < num; ix += 1)
{
v->test[ix].i = 1 + ix;
v->test[ix].data = 1 + ix + (1 + ix) / 100.;
}; // for()
return v;
}
void as_struct_of_struct()
{
V_Test* vector = add_struct();
if (vector->size == 0)
{
printf("No records were created!\n");
free(vector);
return;
}
for ( unsigned count = 0; count < vector->size; count+=1)
{
printf("#%3d: [%d, %.2f]\n",
1 + count,
vector->test[count].i,
vector->test[count].data
);
}; // for()
printf("%d records were created\n", vector->size);
// to free() vector:
free(vector->test);
printf("%d records were free()'d\n", vector->size);
free(vector);
return;
};
void as_vector_of_pointers()
{
Test** vector = add_vector();
// now test the vector to count the number of
// records generated in the funcion
if (vector[0] == NULL)
{
printf("No records were created!\n");
free(vector);
return;
}
unsigned count = 0;
while (vector[count] != NULL)
{
printf("#%3d: [%d, %.2f]\n", 1 + count, (vector[count])->i,
(vector[count])->data);
count += 1;
};
printf("%d records were created\n", count);
// to free() vector, same way:
for (unsigned i = 0; i < count; i += 1) free(vector[i]);
free(vector);
printf("%d records were free()'d\n", count);
return;
}
SO vigilants: I always cast malloc() pointers, as I reminder to
myself and others reading the code. No implicit conversions. No need to pointing that.
I'm trying to add new element to dynamic array in C (I know that I must free all memory. I will do it later), but I get this error every time:
But, what is strange, if I compile from terminal, like that, code works properly.
So, where is the error and how i can beat it?
Thank you!
All my code:
main.c
#include <stdio.h>
#include <stdlib.h>
typedef struct vector
{
int size;
int *array;
int alreadyIn;
}vector;
vector *vectorInit(int size)
{
vector *newVec = (vector *)malloc(sizeof(vector));
if(!newVec){printf("No memory!\n"); return NULL;}
newVec->size = size;
newVec->array = (int *)malloc(size * sizeof(int));
return newVec;
}
void allocNewMemory(vector *vect, int howMuch)
{
vect->array = (int *)realloc(vect->array ,(vect->size + howMuch) * sizeof(int));
vect->size += howMuch;
}
void pushBack(vector *vect, int number)
{
int howMuch = 5;
if(vect && vect->alreadyIn < vect->size)
{
vect->array[vect->alreadyIn] = number;
vect->alreadyIn++;
}
else
{
printf("Alloc new memory for %d elements...\n", howMuch);
allocNewMemory(vect, howMuch);
pushBack(vect, number);
}
}
void printVector(vector *vect)
{
for (int i = 0; i < vect->alreadyIn; i++)
{
printf("%d ", vect->array[i]);
}
printf("\n");
}
int main()
{
int startSize = 4;
vector * vec = vectorInit(startSize);
for (int i = 0; i < 6; i++)
{
pushBack(vec, i+1);
}
printVector(vec);
return 0;
}
You never initialize the alreadyIn member in the structure. That means its value will be indeterminate (and seemingly garbage or random).
You need to explicitly initialize it to zero:
vector *vectorInit(int size)
{
vector *newVec = malloc(sizeof(vector));
if(!newVec)
{
printf("No memory!\n");
return NULL;
}
newVec->size = size;
newVec->array = malloc(size * sizeof(int));
newVec->alreadyIn = 0; // Remember to set this to zero
return newVec;
}
This problem should have been easy to detect in the debugger.
Also note that I removed the casts from malloc. One should not cast the result of malloc, or really any function returning void *.
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).
I have a problem with dynamic arrays in C. My program was working perfectly, but I was asked to put the creation of dynamic array into a seperate void. I did it, and it still worked great, but then I had to assign a value to a certain point of the created array in void, and make it return the said value, however, what I get is a random value. The function works by sending a pointer and the lenght of required array into void, and then makes the pointer into a dynamic array.
#include <stdio.h>
#include <stdlib.h>
#define MAX 255
void ieskom (int skaiciai[],int n, int *de, int *me, int *n1, int *n2)
{
int i = 0;
int j = 0;
int nr1 = 0;
int nr2 = 0;
int temp = 0;
int temp1 = 0;
int eile = 0;
int eile1 = 0;
int *did;
did = (int*)calloc(n,sizeof(int));
if (did==NULL)
{
printf("Nepriskirta atminties.");
exit(0);
}
int *maz;
maz = (int*)calloc(n,sizeof(int));
if (maz==NULL)
{
printf("Nepriskirta atminties.");
exit(0);
}
i = 0;
for (i = 0; i < n; i++)
{
if (skaiciai[i] < skaiciai[i+1])
{
did[j] = did[j] + 1;
if (did[j] > temp)
{
eile = j;
temp = did[j];
nr1 = i+1;
}
}
else
{
did[j] = did[j] + 1;
if (did[j] > temp)
{
eile = j;
temp = did[j];
nr1 = i+1;
}
j = j + 1;
}
}
j = 0;
for (i = 0; i < n; i++)
{
if (skaiciai[i] > skaiciai[i+1])
{
maz[j] = maz[j] + 1;
if (maz[j] > temp1)
{
eile1 = j;
temp1 = maz[j];
nr2 = i+1;
}
}
else
{
maz[j] = maz[j] + 1;
if (maz[j] > temp1)
{
eile1 = j;
temp1 = maz[j];
nr2 = i+1;
}
j = j + 1;
}
}
*de = did[eile];
*me = maz[eile1];
*n1 = nr1;
*n2 = nr2;
free(did);
free(maz);
}
/*int masyvas(x)
{
int y;
y = (int*)malloc(x*sizeof(int));
return y;
}*/
void *masyvas (int *skaiciai, int n)
{
*skaiciai = (int*)malloc(n*sizeof(int));
skaiciai[2] = 5;
return skaiciai;
}
int main()
{
int n1 = 0;
int n2 = 0;
int de = 0;
int me = 0;
int i = 0;
int n = 0;
int *skaiciai;
scanf("%d", &n);
// skaiciai = masyvas(n); // naudojant int
masyvas(&skaiciai, n);
printf("2 = %d", skaiciai[2]);
if (skaiciai==NULL)
{
printf("Nepriskirta atminties.");
exit(0);
}
for (;i < n; i++)
{
scanf("%d", &skaiciai[i]);
}
ieskom (skaiciai, n, &de, &me, &n1, &n2);
if (de > me)
{
printf("Elementu numeriai:");
printf(" %d", n1-de+1);
printf(" %d\n", n1);
printf("\nAtstumas tarp ju: %d", de-2);
}
else
{
printf("Elementu numeriai:");
printf(" %d", n2-me+1);
printf(" %d\n", n2);
printf("\nAtstumas tarp ju: %d", me-2);
}
free(skaiciai);
getchar();
getchar();
return 0;
}
The problem is in void masyvas and printf skaicia[2] - I assign a certain value to skaiciai[2], yet it prints a random one. How do I fix it?
EDIT: Thank you for your answers and explanations, it really helped me a lot! I know have solved my problem, and most importantly, I know why it was a problem in the first place.
First of all, you should translate variables and texts to english (your code lack of comments, this should apply to them too).
Next your masyvas() function returns a pointer to the allocated array (why void* ?!) but when you call it you don't get the returned value.
You have to choose: either you pass a pointer to your function (an array is a pointer, to if you want an array to be allocated from a function you have to pass a pointer to the pointer, so a int **), or you use the returned value.
Allocating with returned value:
// this function allocates a int* tab of size n and set one value
int *allocate_tab(int n) {
int *tmp;
tmp = malloc(n*sizeof(int));
if (tmp == NULL) {
return(NULL); // failed
}
tmp[2] = 5;
return(tmp);
}
// in main (or other function)
int *mytab;
mytab = alloc_tab(45);
Allocating by passing a pointer to the array:
void alloc_tab(int **tab, int n) {
*tab = malloc(n*sizeof(int));
if (*tab == NULL) {
return;
}
(*tab)[2] = 5;
}
// in main (or other)
int *mytab;
alloc_tab(&mytab, 45);
If you can't understand this stuff I guess you should read more about memory, allocation and pointers.
You need to pass a pointer-to-pointer here and do not need to return anything.
void masyvas (int **skaiciai, int n)
{
*skaiciai = (int*)malloc(n*sizeof(int));
(*skaiciai)[2] = 5;
}
When you declare int *skaiciai, the variable is a pointer to type int. skaiciai holds the address that points to an int. When you pass &skaiciai, you're passing the address of the address that points to an int. So because this is an address of an address, its a double pointer.
Here is an example code of what I'm trying to achieve
typedef struct
{
int x_pos, y_pos;
} A;
typedef struct
{
A **arrayAp;
} B;
int main(void) {
B B;
int n = 10;
A *array[n];
B.arrayAp = array;
for (int i = 0; i < 10; i++)
{
B.arrayAp[i] = malloc(sizeof(A));
B.arrayAp[i]->x_pos = i;
B.arrayAp[i]->y_pos = i + 1;
}
printf("%d",B.arrayAp[0]->x_pos);
}
It works as I want it to work. I can access elements of "array" using "arrayAp" pointer. But when I try to move some of this code to function for example:
A * makeAnArray()
{
int n = 10;
A *array[n];
return &array;
}
and then assign value that it returns to "arrayAp"
B.arrayAp = makeAnArray();
Now I can't access first element of the array. Program just crash.
printf("%d",B.arrayAp[0]->x_pos);
But starting from second element everything works the same.
But the bigger problem I get when I try to move to function this code:
void initializeAnArray(B *B)
{
for (int i = 0; i < 10; i++)
{
B->arrayAp[i] = malloc(sizeof(A));
B->arrayAp[i]->x_pos = i;
B->arrayAp[i]->y_pos = i + 1;
}
}
Seems like it has no effect. When i'm trying to access array member through "arrayAp" pointer i'm getting some "random" values from memory.
typedef struct
{
int x_pos, y_pos;
} A;
typedef struct
{
A **arrayAp;
} B;
A * makeAnArray()
{
int n = 10;
A *array[n];
return &array;
}
void initializeAnArray(B *B)
{
for (int i = 0; i < 10; i++)
{
B->arrayAp[i] = malloc(sizeof(A));
B->arrayAp[i]->x_pos = i;
B->arrayAp[i]->y_pos = i + 1;
}
}
int main(void) {
B B;
B.arrayAp = makeAnArray();
initializeAnArray(&B);
printf("%d",B.arrayAp[1]->x_pos);
}
Sorry for my poor English.
Your function should be:
A * makeAnArray()
{
int n = 10;
//A *array[n]; --> This is local to this function so won't work
A *array = malloc(sizeof(A)*n); //--> Dynamic allocation
return array;
}
A * makeAnArray()
{
int n = 10;
A *array[n];
return &array;
}
You are returning a local pointer which dies after the function ends and causes UB.
Moreover return type of your function should be A** and you should allocate memory with *alloc and return to ensure every instance is different and is alive after the function call.
Possible fix
A * makeAnArray()
{
int n = 10;
A *array = malloc(n * sizeof(A));
return array;
}
The part
A * makeAnArray()
{
int n = 10;
A *array[n];
return &array;
}
is not going to work. The array array might be allocated on the stack, it cannot be accessed via the return value after termination of makeAnArray; the result is undefined behaviour.