August 3rd, 2003, 09:25 PM
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.
August 3rd, 2003, 10:30 PM
You can use the strlen() function in <cstring> to find the length of string1:
Or, you can step through str1 using array notation(e.g. str1, str1, 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 10:39 PM.
August 3rd, 2003, 11:48 PM
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.
August 4th, 2003, 12:29 AM
sizeof(values) gets the total number of bytes occupied by the array, and sizeof(values) 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 4th, 2003 at 12:36 AM.
August 4th, 2003, 01:48 PM
I don't think sizeof works for dynamicly created arrays, ie:
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:
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.