# finding size of char*

• 06-16-2005
JoshR
finding size of char*
I have been struggling for a long time trying different sizeof algorithms ive made up to find out how many objects are in the array. How can i do this??? I used sample code from charlez petzolds book and i have used the same algorithm and it works in his but not mine. so please help.
• 06-16-2005
ay_okay
for finding the size of a char, include the string.h or cstring lib and use the function:
Code:

`int strlen(const char *string);`
example
Code:

```char string[30] = "Hello World"; cout<<"The char is "<<strlen(string)<<" characters long"<<endl;```
• 06-16-2005
xErath
Quote:

Originally Posted by JoshR
I have been struggling for a long time trying different sizeof algorithms ive made up to find out how many objects are in the array. How can i do this??? I used sample code from charlez petzolds book and i have used the same algorithm and it works in his but not mine. so please help.

basiclly you cant' in most of the times..

Code:

```char b[10]; sizeof(b) returns sizeof(char) which is 1 times 10 int f(char b[]){return sizeof(b);} f(b) returns sizeof(char*) because only a pointer is passed, and not the whole array. char *c = new char[10]; sizeof(c) returns sizeof(char*), usually a 32 bits memory adress```
So you'll have to keep track of the number of elements stored.
• 06-16-2005
JoshR
thanks a lot ay_okay
• 06-17-2005
7stud
1) When you declare an array, you have to know the size to begin with. For instance,
Code:

```const int size = 3; double myArray[size] = {1.5, 2.5, 3.5}; cout<<"The size of the array is: "<<size<<endl;```
If you want to send the array to a function and inside the function you need to know the size, then you should define the function to also accept the size of the array. For instance,
Code:

```void myFunc(double anArray[], int size) {         for(int i = 0; i<size; i++)         {                 cout<<anArray[i]<<endl;         } }```
2) If you insist on using sizeof to get the size of the array, you can use an expression like this:

sizeof arrayName/sizeof arrayName[0]

For instance,
Code:

```#include <iostream> using namespace std; class Apple { public:         int weight; }; int main () {         const int size = 3;         Apple appleArray[size];                 for(int i = 0; i < sizeof appleArray/sizeof appleArray[0]; i++)         {                 appleArray[i].weight = i+1;         }         for(i= 0; i < sizeof appleArray/sizeof appleArray[0]; i++)         {                 cout<<appleArray[i].weight<<endl;         }         return 0; }```