473,770 Members | 4,419 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

sizeof dinamically alocated array....

I have char *array and it is dinamically alocated....
When I pass it to other function, I need to determine size of this array....
Problem: sizeof operator does not work with dinamically alocated
arrays!?!?!

How can I determine size of dinamically alocated array.... ?
Please advice...
Thx!
Mar 11 '06 #1
32 2678
Mateo wrote:
I have char *array and it is dinamically alocated....
When I pass it to other function, I need to determine size of this
array.... Problem: sizeof operator does not work with dinamically
alocated arrays!?!?!

How can I determine size of dinamically alocated array.... ?


You cannot. You need to store the size at the time of allocation
and pass it into the same function. If you can't do that, do not
use a plain char array, use 'std::string'.

V
--
Please remove capital As from my address when replying by mail
Mar 11 '06 #2
Mateo wrote:
I have char *array and it is dinamically alocated....
When I pass it to other function, I need to determine size of this
array....
Problem: sizeof operator does not work with dinamically alocated
arrays!?!?!

How can I determine size of dinamically alocated array.... ?


This is a Frequently Asked Question, but I don't know if it's in the FAQ.

The answer is you should use an std::vector<> unless you actually need a
primitive array, returned by new[].

If you have a legitimate reason not to use std::vector<>, then pass the size
with the array.

There's no portable way to get this information, because your program is
essentially throwing the information away after the new[] call. Don't.

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Mar 11 '06 #3
Phlip wrote:

The answer is you should use an std::vector<> unless you actually need a
primitive array, returned by new[].


Not to mention that for passing to library/OS routines that require a
naked T*, a std::vector<T> is trivially convertable to a T* by passing
&v[0].

Mar 11 '06 #4

Victor Bazarov wrote in message ...
Mateo wrote:
I have char *array and it is dinamically alocated....
When I pass it to other function, I need to determine size of this
array.... Problem: sizeof operator does not work with dinamically
alocated arrays!?!?!

How can I determine size of dinamically alocated array.... ?


You cannot. You need to store the size at the time of allocation
and pass it into the same function. If you can't do that, do not
use a plain char array, use 'std::string'.
V
--


Well, there's always the 'Three Stooges' method:

size_t SomeFunc( char /* const */ *MyCharArray ){
std::string ForSize( MyCharArray );
size_t ArrSize( ForSize.size() );
// Do something with MyCharArray that needs size.
// don't forget to add 1 if you need to include
// the '\0' at end of array.
return ArrSize;
// size_t ArrSize = sizeof( MyCharArray );
// return ArrSize; // returns 4 (the size of pointer)
}

int main(){
char MyCharArray[] = "abcd1234xy z";
std::cout<<"Som eFunc( MyCharArray ); "
<<SomeFunc( MyCharArray )<<std::endl;
return 0;
}
// output: SomeFunc( MyCharArray ); 11

--
Bob <G> R
POVrookie
Mar 12 '06 #5
BobR wrote:
Victor Bazarov wrote in message ...
Mateo wrote:
I have char *array and it is dinamically alocated....
When I pass it to other function, I need to determine size of this
array.... Problem: sizeof operator does not work with dinamically
alocated arrays!?!?!

How can I determine size of dinamically alocated array.... ?


You cannot. You need to store the size at the time of allocation
and pass it into the same function. If you can't do that, do not
use a plain char array, use 'std::string'.
V
--


Well, there's always the 'Three Stooges' method:

size_t SomeFunc( char /* const */ *MyCharArray ){
std::string ForSize( MyCharArray );
size_t ArrSize( ForSize.size() );
// Do something with MyCharArray that needs size.
// don't forget to add 1 if you need to include
// the '\0' at end of array.
return ArrSize;
// size_t ArrSize = sizeof( MyCharArray );
// return ArrSize; // returns 4 (the size of pointer)
}

int main(){
char MyCharArray[] = "abcd1234xy z";
std::cout<<"Som eFunc( MyCharArray ); "
<<SomeFunc( MyCharArray )<<std::endl;
return 0;
}
// output: SomeFunc( MyCharArray ); 11


I believe you've confused the size of the array with the length of
a C string stored in it. Show it again with this 'MyCharArray':

int main() {
char MyCharArray[] = "abc\0def\0ghi\ 0jkl\0\0\0";
...

V
--
Please remove capital As from my address when replying by mail
Mar 12 '06 #6

Victor Bazarov wrote in message ...
BobR wrote:
Victor Bazarov wrote in message ...
Mateo wrote: [snip] How can I determine size of dinamically alocated array.... ?

You cannot. You need to store the size at the time of allocation
and pass it into the same function. If you can't do that, do not
use a plain char array, use 'std::string'.
V
--


Well, there's always the 'Three Stooges' method:

size_t SomeFunc( char /* const */ *MyCharArray ){
std::string ForSize( MyCharArray );
size_t ArrSize( ForSize.size() );
// Do something with MyCharArray that needs size.
return ArrSize;
}

int main(){
char MyCharArray[] = "abcd1234xy z";
std::cout<<"Som eFunc( MyCharArray ); "
<<SomeFunc( MyCharArray )<<std::endl;
return 0;
}
// output: SomeFunc( MyCharArray ); 11


I believe you've confused the size of the array with the length of
a C string stored in it. Show it again with this 'MyCharArray':

int main() {
char MyCharArray[] = "abc\0def\0ghi\ 0jkl\0\0\0";
...
V
--


Well, there's always the 'Three Stooges + Mickey Mouse' method: <G>

size_t SomeFunc2( char *MyCharArray ){
std::string ForSize( MyCharArray ); // the Mickey
std::string Look(3, '\0'); // the Mouse
size_t index( ForSize.size() );
while( ForSize.find( Look ) == std::string::np os ){
ForSize.push_ba ck( MyCharArray[index] );
++index;
}
size_t ArrSize( ForSize.size() );
// Do something with MyCharArray.
return ArrSize;
}

int main(){
char MyCharArray[] = "abc\0def\0ghi\ 0jkl\0\0\0";
std::cout<<"Som eFunc2( MyCharArray ); "
<<SomeFunc2( MyCharArray )<<std::endl;

std::cout<<"siz eof(MyCharArray )/sizeof(*MyCharA rray) "
<<sizeof(MyChar Array)/sizeof(*MyCharA rray)<<std::end l;
return 0;
}
// -- output --
// SomeFunc2( MyCharArray ); 18
// sizeof(MyCharAr ray)/sizeof(*MyCharA rray) 19

Either:
a - You have no sense of humor.
or
b - I've been had, and I tip my hat to you.

--
Bob R
POVrookie
Mar 12 '06 #7
Vector is the way to go.

I have read in Meyers that &v[0] is not advisable unless v.size () > 0.

red floyd wrote:
Phlip wrote:

The answer is you should use an std::vector<> unless you actually need a
primitive array, returned by new[].


Not to mention that for passing to library/OS routines that require a
naked T*, a std::vector<T> is trivially convertable to a T* by passing
&v[0].


Mar 12 '06 #8
AnonMail2005 wrote:
Vector is the way to go.

I have read in Meyers that &v[0] is not advisable unless v.size () > 0.


To the intermediates:

Bow before /C++ Coding Standards : 101 Rules, Guidelines, and Best
Practices/ (C++ in Depth Series) by Herb Sutter & Andrei Alexandrescu. It
covers such scratchy situations as interfacing to a C API that likes raw
pointers.

They advise the &v[0] trick, and I can't recall if they warn about the
size() == 0 situation.

Now I thought that all containers always have a valid .begin() and .end(),
and if they equal then the container is empty, so this might suggest that
&v[0] is always valid (whereas v[0] is not, because it dereferences an
unconstructed object).

So where am I wrong?

To the newbies:

The original poster appeared to be writing their own function that takes a
pointer. If so, they should avoid pointers (as should coders at all levels),
and should pass a reference to a vector:

typedef std::vector<int > ints_type;
void foo(ints_type & ints);

References have fewer features, so they are always better than pointers, and
vectors have more features than arrays, so they are always better than
arrays.

Always pick the technique with fewer features. Or more features. I'll try
again.

Always pick the technique with the safest features. Raw pointers have many
unsafe features, and vectors have many safe ones.

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Mar 12 '06 #9
Mateo posted:
I have char *array and it is dinamically alocated....
When I pass it to other function, I need to determine size of this
array.... Problem: sizeof operator does not work with dinamically
alocated arrays!?!?!

How can I determine size of dinamically alocated array.... ?
Please advice...
Thx!

#include <cstddef>
#include <iostream>
using std::cout;
using std::endl;
template<std::s ize_t i>
void PrintStringLeng th( char (&str)[i] )
{
cout << "This string is " << (i - 1) << " characters long.\n";
}

int main()
{
char (&str)[7] = * reinterpret_cas t< char (*)[7] > ( new char[7] );

std::strcpy(str , "monkey");
PrintStringLeng th(str);

}
-Tomás
Mar 12 '06 #10

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

Similar topics

33
12867
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) {
2
2469
by: Xiangliang Meng | last post by:
Hi, all. What will we get from sizeof(a class without data members and virtual functions)? For example: class abnormity { public: string name() { return "abnormity"; }
7
4636
by: nzanella | last post by:
Hello, I just thought I would share the following observation with the rest of the group. The sizeof operator seems to act differently according to whether the number of elements in the array is known. Hence when passing arrays to functions the number of elements in the array must always be passed as an argument. If STL is available then people can just use vectors of course. Anyways, I guess this stuff is pretty standard. Well, have a...
15
6252
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);
15
15168
by: ak | last post by:
struct xy{ int x; int y; } _xy; size_of_xy(struct xy * a) { int len = sizeof a; printf( "\sizeof xy: %i\n", len ); }
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));
3
2681
by: valerio | last post by:
Hello all I would like to dinamically allocate an array of array of structures. To explain this: struct file{ char* fileName,int inode) myfiles; struct file{ char* fileName,int inode) mydirs; but I would like to do it dinamically with linked list. I am able to do it for myfiles, but not with mydirs. Pseudo-code is ok.
58
7203
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>
8
1967
by: c.lang.myself | last post by:
whenever we pass an array to function, we have to also pass its size.e.g if i am making a soritng function then void sort(int b,int size); Now I thought about using sizeof operator(macro?) inside sort function on b and get size of b i.e by sizeof(b)/sizeof (b) but i am not getting correct result.....
0
9602
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
9439
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
10237
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...
1
10017
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
9882
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
6690
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5326
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5467
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3589
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.