Home › Forums › C Programming › Getting the length of an array
- This topic has 2 replies, 2 voices, and was last updated 16 years, 3 months ago by glimpse.
- AuthorPosts
- September 4, 2008 at 12:10 am #2132glimpseParticipant
Dear friends,
When I allocate memory for an array, can I afterwards get an information about the size of the allocated memory?
The background is a simple function named vectorsum, that I programmed.
That is:12345678float vectorsum(float* vector,int length)<br />{<br />int i=0;<br />float sum=0;<br />for(i=0;i<length;i++)<br />sum+=vector;<br />return sum;<br />}I find it a bit stupid, that I have to give the length to the function and it is also bad, that it is restricted to one data type (float*).
I would be glad to get a fast answer from you.
Thank you in advance. - September 4, 2008 at 11:45 am #3444HumayanParticipant
I don’t think you can information about data requested from the “heap” . The operating system simply returns an address of the dynamic memory from the heap area of the correct size , so I don’t think there is any way to recover this information ( so sending the length of the vector to a function is a good idea ).
- September 4, 2008 at 10:13 pm #3445glimpseParticipantThank you. I also can’t imagine how it works. I thought about strings and the function strlen…
Somehow the program allocates memory and may not write anything else into this memory. The program also has to know the size of the array, when it wants to free the memory again. The information is somewhere. Maybe there is also a kind of end tag at the end of the allocated memory. But that is for sure a very sophisticated matter.Pharao
- AuthorPosts
- The forum ‘C Programming’ is closed to new topics and replies.