Reputation: 133
/* Write a function that returns the length of a string(char *), excluding the final NULL character.It should not use any standard - library functions.You may use arithmetic and dereference operators, but not the indexing operator ([]) */
#include "stdafx.h"
#include<iostream>
using namespace std;
int stringLength(const char * str) {
int length = 0;
while (*(str + length) != '\0') {
++length;
cout << length;
return length;
}
int _tmain(int argc, _TCHAR* argv[]){
stringLength({ 'a', 'b', 'c', '\0' });
return 0;
}
Somehow I think I am not calling my function properly in the main function, but I am not sure how else I should do it. What is the proper way of calling a function of this type? (Sorry if this is a stupid question: I am new to C++)
Upvotes: 0
Views: 121
Reputation: 613242
Pass a string. For instance
int len = stringLength("abc");
FWIW, it would be idiomatic to use size_t
for the return type of this function. When you try to work with other code you'll meet resistance to having used int
rather than size_t
.
The code in the question is also rather poorly formatted and does not compile. You omitted a closing brace. It pays to get this sort of detail just right.
Upvotes: 1
Reputation: 35438
Like: int l = stringLength("abc");
C constant strings are automatically zero terminated, so you don't need to specify the extra zero character.
Upvotes: 1