I have trouble with getting the correct number of characters displayed when returning this simple function. Does anyone see what I am doing wrong in the function (the cout function outputs -2 instead of 4 which is the lenght of "test")? Thanks:

#include <iostream>
using namespace std;

int mystrlen(char *ptr, int nums);  //function prototype for mystrlen

int main() {

    char arr[]="test";  // define the array
    int i, num;

    mystrlen(arr, num); // send arguments to function 

    cout << "Print string text " << arr << endl; 
    cout << "Print string lenght: " << num-1;   

    return 0;
}
int mystrlen(char *ptr, int nums) { 

    for(i=0; ptr[i]; i++) nums+= i;  // count characters in ptr
    cout << nums-1 << endl; // correct number of characters (4)!!

    return (ptr, nums); // return ptr and nums into arr and num

    }

You see, you declared num. Now num points to a 4byte block which contains a garbage information. So when you are calling mysterlen, you are giving whatever happened to be stored in that block of memory. What you want to do is set num to 0 before you call the function. (btw, you don't really need to pass num as an argument anyway, you can just declare num inside mysterlen function)

Your way off :)

First of all you can't access a variable outside of its own scope, you are using the variable i in the function mystrlen, though it was created in the main function.

If you want to make the function mystrlen return the length of ptr, simply loop through each char until the null-char is reached, and return the index of that character. The change is simple.

int mystrlen(char *ptr) { 
   int i; // Length of ptr
   for (i = 0; ptr[i]; i++); // Loop until null-char is reached
   return i; // Return length
}

And then you could change your main function to:

int main() {
    char arr[] = "test";
    int num;

    num = mystrlen(arr);

    cout << "Print string text " << arr << endl; 
    cout << "Print string lenght: " << num;   

    return 0;
}

Hope this helps.

Hope this helps.

Thanks, yes this certainly helped.

Edited 3 Years Ago by Reverend Jim: Fixed formatting

This article has been dead for over six months. Start a new discussion instead.