Thursday 30 November 2017

c - MPI dynamic array using malloc

itemprop="text">

I am having problem while creating
dynamic array using both malloc and
calloc.





int main()
{
float *xd_real_send;
int Nooflines_Real;
int
*X;

float test[500];

Nooflines_Real =
count_lines(infile);
printf("Nooflines_Real: %d\n",
Nooflines_Real);

X = (int *)
malloc(Nooflines_Real*sizeof(int));
xd_real_send = (float *) calloc
(Nooflines_Real,sizeof(float));

printf("size of X %d, test %d and
size of xd_real_send %d\n",

sizeof(X)/sizeof(int),sizeof(test)/sizeof(float),


sizeof(xd_real_send)/sizeof(float));fflush(stdout);


}



And the output is




Nooflines_Real:
40

size of X 2, test 500 and size of xd_real_send
2


Could you please tell what Am I
doing wrong.


itemprop="text">
class="normal">Answer




X and
xd_real_send are defined as pointers.



The sizeof operator
applied returns the amount of memory use by the pointer, not the size of what the
pointer refers to.



It not possible (in any
portable way) to request the size of a memory block once allocated dynamically and
refered by some pointer.




For
dynamically allocated memory the application needs to take care of keeping track of how
large those memory blocks are.



/>

test is defined expliciltly
as an array, so sizeof is able to determine the array's size.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...