### Thread: Finding length of array?

1. #### Finding length of array?

I am writing a strcpy function, but I want to determine if string1 is big enough to hold string2? right now it's just s(char *str1, char *str2) and loops filling up str1.. I will also have something like strcpyn.
2. No Profile Picture
Contributing User
Devshed Beginner (1000 - 1499 posts)

Join Date
Feb 2001
Posts
1,481
Rep Power
18
You can use the strlen() function in <cstring> to find the length of string1:

strlen(string1)

Or, you can step through str1 using array notation(e.g. str1[0], str1[1], etc.) and count the characters, until you hit a \0 which is tacked onto the end of every c-string.
Last edited by 7stud; August 3rd, 2003 at 09:39 PM.
3. No, what if the array is int? or it's full of garbage data, but I guess you CAN't because you WILL always know the array size, since it can't be dynamic.
4. No Profile Picture
Contributing User
Devshed Beginner (1000 - 1499 posts)

Join Date
Feb 2001
Posts
1,481
Rep Power
18
int values[20];

int values_length=sizeof(values)/sizeof(values[0]);

sizeof(values) gets the total number of bytes occupied by the array, and sizeof(values[0]) gets the number of bytes occupied by the first element(which is the same as every other element).

I hadn't thought of the case where a char array hasn't been initialized and is full of garbage values. The above solution will work for any array type--whether it has garbage values or not.
Last edited by 7stud; August 3rd, 2003 at 11:36 PM.
5. I don't think sizeof works for dynamicly created arrays, ie:
Code:
```int *x;
x=new int[100];```
What you would usually do is store the size as a seperate value.

If you know the array will be fairly small, you can store it as a pascal string.

A pascal string has it's first array element an unsigned byte representing the length of the string. ie:
Code:
```char *x;
x=new char[3];
x[0]=2;
x[1]='h';
x[2]='i';```
Of course, the best way to solve the problem is just to always remember to initialize all your strings with a null (0) character as the first byte.