EXC_BAD_ACCESS?

1
2
3
4
5
6
7
8
9
int sizeofarray(char array[200])
{
    int n;
	
    for (int i = 0; array[n]; i++) {
        n++;
    }
    return n;
}


This function worked fine until I put it into a header file and used it in another function in the main file.

help??
You are not initializing n to zero before using it. I wonder how this ever worked OK.

Question: What happens if array[n] is never zero? This can happen if the array is fully utilized. Also it should be array[i]. Variable i is the variable used to traverse the array. Variable n is just an accumulated result.

Finally, this is memory-inefficient. C++ will make a copy of the entire array every time this function is called.
Thanks. This is the only way I know to find the size of a character array. Is there a better way that's not so memory inefficient?
You could use: strlen(). Which will return the count of characters up until the NULL at the end '/0'.

1
2
3
4
5
6
7
8
char myArray[ 200 ];

std::cout << "Enter come text: ";
std::cin.getline( myArray, 200, '\n' );

std::cout << "You entered: " << myArray << '\n';

std::cout << "Letter count: " << strlen( myArray ) << '\n';


+1 to strlen(). I did not mention it because I figured this was part of an assignment. Use strlen() if you are not bound to use sizeofarray() for academic purposes.
Finally, this is memory-inefficient. C++ will make a copy of the entire array every time this function is called.
Nope, arrays are passed by reference.

You may want to look at std::string
Wow, I just read this: http://www.cplusplus.com/doc/tutorial/arrays/.

So no memory inefficiency here then. Good to know.
Topic archived. No new replies allowed.