MN <mazouz.nezhate@gmail.comwrote:
Quote:
How to store the function's result into variable in this case?
My code is like this::
Quote:
#include <stdio.h>
#include <stdlib.h>
Why do you declare it as extern if you define it just
two lines later?
Quote:
int* function(int in1, int in2);
Quote:
int* var1 =NULL;
int* view_var1 =NULL;
Quote:
int main ()
{
int i = 0;
//extern int* view_var1;
int in1 = 5;
int in2 = 10;
Quote:
/* if (view_var1 != NULL) */
/* free(view_var1); */
Quote:
/* view_var1 = (int*)malloc (sizeof(int*)* in2); */
'view_var' seems to be supposed to be a pointer to int, at
least that's how you defined it. Then this line is wrong,
since you allocate room for 'in2' pointers to int, and
not for 'in2' ints. You also shouldn't cast the return
value of malloc() - the conversion from void pointer to
the left hand side type happens all by itself, but the
cast will keep the compiler from warning you when you
forget to include <stdlib.h>. So make that line
view_var = malloc( in2 * sizeof( int ) );
or, perhaps better
view_var = malloc( in2 * sizeof *view_var );
You may have got away with your faulty version since on
a number of systems an int and a pointer to int take
the same amount of room, but that's nothing you should
rely on.
Quote:
/* view_var1 = function(in1, in2); */
Quote:
function(in1, in2);
Quote:
for (i = 0; i < in2; i++)
{
if (i == 0)
//printf("- %d\n", &view_var1[i]);
'&view_var1[i]' is a pointer to the element with index 'i'
of the 'view_var' array and not an integer. Simply drop
the '&'.
Quote:
printf("- %d\n",var1[i]);
Quote:
else
//printf("%d %d\n", i-1, &view_var1[i]);
Same her.
Quote:
printf("%d %d\n", i-1, var1[i]);
}
return 0;
Quote:
int* function(int in1, int in2)
{
int i = 0;
if (var1 != NULL)
free(var1);
var1 = (int*)malloc (sizeof(int*)* in2);
Here's the same problem as above, you need
var1 = malloc( in2 * sizeof *var1 );
Quote:
for (i = 0; i < in2; i++)
{
if (i == 0)
var1 [i] = 0;
else
{
if (i == 1)
var1[i]= 1;
else
var1[i] = var1[ i - 1 ] * 2 + in1;
}
}
return (var1[in2]);
This will return an int, not, as the function is defined to,
a pointer to int. I guess you wanted to do
return var1;
Regards, Jens
--
\ Jens Thoms Toerring ___
jt@toerring.de
\__________________________
http://toerring.de