473,757 Members | 10,736 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

sizeof dynamic array

D
hi,

i would like to know how to calculate the size of a dynamic array
created using a dereference declaration like int *numbers and
allocating via malloc or calloc: numbers=(int
*)malloc(sizeof (int)*10);

using sizeof(numbers) will return the pointers size...

is there a possibility?

D@nny
--
life already is expensive, so why waste money on expensive
software.
Nov 14 '05 #1
11 12035
"D@nny" <no@thanx.nl> wrote in message
news:fZ******** ********@amsnew s03-serv.chello.com ...
hi,

i would like to know how to calculate the size of a dynamic array
Determine how big you need it to be, and allocate that much.
created using a dereference declaration like int *numbers
That's not a 'dereference declaration'. Its a declaration
of a pointer object.
and
allocating via malloc or calloc: numbers=(int
*)malloc(sizeof (int)*10);
Never cast the return value from 'malloc()'. See the FAQ
for details.

using sizeof(numbers) will return the pointers size...
Yes. Because 'numbers' is a pointer.

is there a possibility?


Yes. You know the size when you allocate it. Just retain
that value (i.e. store it in a 'size_t' object).

int *numbers = 0;
size_t sz = 10 * sizeof *numbers;

if(numbers = malloc(sz))
{
printf("%lu bytes allocated.\n", (unsigned long)sz);
/* do stuff */
free(numbers);
}

-Mike
Nov 14 '05 #2
D@nny wrote:
hi,

i would like to know how to calculate the size of a dynamic array
created using a dereference declaration like int *numbers and
allocating via malloc or calloc: numbers=(int *)malloc(sizeof (int)*10);
Guess what: the size of the array is sizeof(int)*10. What did you think
it was.

BTW, your code line above is not, at least here, idiomatic. Had you
lurked before posting (expected usenet behavior) or checked the FAQ
before posting (expected usenet behavior), you would have no this.

You have no idea how many people everyday violate those two standard
rules every day just to post code that casts the return value from
malloc (corrected several times a day here), uses hard-coded magic
numbers, uses hard-coded data types in allocation statements, asks
questions answered multiple times a week (as is yours), and fails to
include a compilable example.

#include <stdlib.h>
int main(void)
{
const number_elements = 10;
int *numbers;
numbers = malloc(number_e lements * sizeof *numbers);
if (!numbers) { /* handle error */ }
else free(numbers);
return 0;
}
using sizeof(numbers) will return the pointers size...

is there a possibility?


Obviously, there is. If you can figure out how much space to ask malloc
for, you already know the answer.
Nov 14 '05 #3
D@nny <no@thanx.nl> scribbled the following:
hi, i would like to know how to calculate the size of a dynamic array
created using a dereference declaration like int *numbers and
allocating via malloc or calloc: numbers=(int
*)malloc(sizeof (int)*10); using sizeof(numbers) will return the pointers size... is there a possibility?


Not in standard C. You'll have to use implementation-specific tricks.
But since you know the size when you allocate the memory, why not simply
keep track of it?

--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ------------- Finland --------\
\-------------------------------------------------------- rules! --------/
"To know me IS to love me."
- JIPsoft
Nov 14 '05 #4


D@nny wrote:
hi,

i would like to know how to calculate the size of a dynamic array
created using a dereference declaration like int *numbers and
allocating via malloc or calloc: numbers=(int
*)malloc(sizeof (int)*10);

using sizeof(numbers) will return the pointers size...

is there a possibility?


What you should do is declare a variable, ex. size_t nelements,
that you can use to store the number of elements allocated for
the int array. If you dynamically allocated the array for
10 elements, then store in nelements the value 10. If you
modify the number of array elements, then modify nelements
appropriately. In the occasion where you might need the
total size of the allocation, just multiply the sizeof(int)
with nelements.

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
int *iarr, *tmp;
size_t nelements = 0;

iarr = malloc((sizeof *iarr)*10);
if(iarr) nelements = 10;
printf("Number of elements allocated is %u\n"
"Size of the allocation is %u\n\n",
nelements, nelements*sizeo f(int));
if(nelements)
{
puts("An attempt to increase the allocation one element\n");
tmp = realloc(iarr,(s izeof *iarr)*(nelemen ts+1));
if(tmp)
{
iarr = tmp;
nelements++;
}
printf("Number of elements allocated is %u\n"
"Size of the allocation is %u\n\n",
nelements, nelements*sizeo f(int));
}
free(iarr);
return 0;
}
--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapi dsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 14 '05 #5

"Mike Wahler" <mk******@mkwah ler.net> wrote in message
news:cf******** *********@newsr ead3.news.pas.e arthlink.net...
"D@nny" <no@thanx.nl> wrote in message
news:fZ******** ********@amsnew s03-serv.chello.com ...
hi,

i would like to know how to calculate the size of a dynamic array


Determine how big you need it to be, and allocate that much.
created using a dereference declaration like int *numbers


That's not a 'dereference declaration'. Its a declaration
of a pointer object.
and
allocating via malloc or calloc: numbers=(int
*)malloc(sizeof (int)*10);


Never cast the return value from 'malloc()'. See the FAQ
for details.


Hello I am not the original poster... but this seems interesting.

I can't the answer in this FAQ;

http://www.eskimo.com/~scs/C-faq/s7.html

Why shouldn't it be typecasted ?

1. Maybe because it doesn't compile on true c compilers ?

2. Or does it lead to bugs ?

Bye,
Skybuck.
Nov 14 '05 #6
On Sun, 7 Nov 2004 15:47:26 +0100, "Skybuck Flying"
<no****@hotmail .com> wrote:

"Mike Wahler" <mk******@mkwah ler.net> wrote in message
news:cf******* **********@news read3.news.pas. earthlink.net.. .


snip
Never cast the return value from 'malloc()'. See the FAQ
for details.


Hello I am not the original poster... but this seems interesting.

I can't the answer in this FAQ;

http://www.eskimo.com/~scs/C-faq/s7.html

Why shouldn't it be typecasted ?


a. It is unnecessary in C. Superfluous casts should always be
avoided.

b. It leads to undefined behavior (under C89, currently the standard
implemented by most popular compilers) if the prototype for malloc is
omitted.
<<Remove the del for email>>
Nov 14 '05 #7

"D@nny" <no@thanx.nl> wrote in message
news:fZ******** ********@amsnew s03-serv.chello.com ...
hi,

i would like to know how to calculate the size of a dynamic array
created using a dereference declaration like int *numbers and
allocating via malloc or calloc: numbers=(int
*)malloc(sizeof (int)*10);

using sizeof(numbers) will return the pointers size...

is there a possibility?


As others have mentioned, keep track of the size when you allocate the
array.

I suppose one possible exception is a null-terminated char array where you
can call 'strlen' to get the length of the array.
Nov 14 '05 #8

Method Man wrote:
"D@nny" <no@thanx.nl> wrote in message
news:fZ******** ********@amsnew s03-serv.chello.com ...
hi,

i would like to know how to calculate the size of a dynamic array
As others have mentioned, keep track of the size when you allocate the array.

I suppose one possible exception is a null-terminated char array where you can call 'strlen' to get the length of the array.


That gives you length of the string, not the size of the array. They
are often different. So for instance, you have no way of knowing
whether you can extend the string safely unless you know the size of
the underlying array.

Brian

Nov 14 '05 #9

"Method Man" <a@b.c> wrote in message
news:H1******** ***********@rea d2.cgocable.net ...

"D@nny" <no@thanx.nl> wrote in message
news:fZ******** ********@amsnew s03-serv.chello.com ...
hi,

i would like to know how to calculate the size of a dynamic array
created using a dereference declaration like int *numbers and
allocating via malloc or calloc: numbers=(int
*)malloc(sizeof (int)*10);

using sizeof(numbers) will return the pointers size...

is there a possibility?


As others have mentioned, keep track of the size when you allocate the
array.

I suppose one possible exception is a null-terminated char array where you
can call 'strlen' to get the length of the array.


char *array = malloc(100);
size_t sz = 0;

if(array)
{
strcpy(array, "Hello");
sz = strlen(array); /* sz != 100 */
}

free(array);

-Mike
Nov 14 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

33
12863
by: Metzen | last post by:
hello, ok, I want to find the length of an int array that is being passed to a function: main() { int array={1,2,3,4,5,6,7,8}; function(array); } function(int *array) {
15
6249
by: fdunne2 | last post by:
The following C-code implements a simple FIR filter: //realtime filter demo #include <stdio.h> #include <stdlib.h> //function defination float rtFilter1(float *num, float *den, float *xPrev, float *yPrev);
8
2538
by: junky_fellow | last post by:
Consider the following piece of code: #include <stddef.h> int main (void) { int i, j=1; char c; printf("\nsize =%lu\n", sizeof(i+j));
74
4686
by: ballpointpenthief | last post by:
If I have malloc()'ed a pointer and want to read from it as if it were an array, I need to know that I won't be reading past the last index. If this is a pointer to a pointer, a common technique seems to be setting a NULL pointer to the end of the list, and here we know that the allocated memory has been exhausted. All good. When this is a pointer to another type, say int, I could have a variable that records how much memory is being...
2
3310
by: flyvholm | last post by:
According to a couple of other threads you can't use sizeof with dynamic arrays - you'll have to keep track of the memory allocated. In my case, strings are filled into a dynamic array by a database query (postgresql), meaning that it is not readily possible to keep track (a preprocessor converts the database query to C code, using some functions that in turn do the memory allocation). I want to hand the array to a function that needs to make...
58
7199
by: Nishu | last post by:
Hi All, When I run the below program in MSVC, I get the output as 1 4 Could you tell me why sizeof 'A' is taken as 4? Is it standard defined or compiler specific? Thanks, Nishu /**************************************/ #include<stdio.h>
9
15283
by: Faisal | last post by:
Hi, Why C++ doesn't allow overloading of size of operator. I think it would be much handy to check the type userdefined types. For eg. In my project, I've some structures which contains dynamic data( pointers). So if i have some way to overload the sizeof operator I can calculate the exact size and return.
7
3117
by: alternative451 | last post by:
Hi, I have just one question : how to know the size of an array, i have un little program, i use first static, ant i can use sizeof() to know the size, but when i put it as paremeter in the function, size of return "1". ex int tab; printf("%d",sizeof(tab)/sizeof(int)); // print 10 int length(int *tab)
27
5603
by: CodeMonk3y | last post by:
gotta question on sizeof keyword does the sizeof keyword calcuates the size at compile time or run time ?? -- Posted on news://freenews.netfront.net - Complaints to news@netfront.net --
0
9489
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9298
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10072
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9906
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9885
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9737
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5329
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3829
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2698
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.