chessc4c6 wrote:
>
> ok, since I've posted this question and doing some research, I've come
> up with this code:
> #include <iostream>
> using namespace std;
> long strlen(char *s1){
> long count;
> s1=new char[10];
What is the memory allocation doing in here?
You already have a pointer to the beginning
of a valid string: it was passed as argument
to the function.
> count=0;
> while (s1 != '/0'){
You don't want to check if the pointer equals '\0'
(whatever that may mean). You want to check if the thing
the pointer *points to* equals '\0'
while( *s1 != '\0' ) {
Note: the '*' which makes all the difference.
> count+=1;
or more idiomatic
cout++;
> s1++;
> }
> return count;
> }
> void main(){
int main() {
> long strlen(char *s1);
> cout <<"The length of the string JAIME is" << strlen("JAIME") <<endl;
> }
>
> The whole purpose is to use long strlen(char *s1) using a while loop
> and a pointer
> representing the string will be used.Now I get errors doing this and
> I'm not sure if its correct.
> I used s1=new char[10] to dynamically allocate memory.
What for?
I mean, what do you need this dynamic allocated memory for?
In:
I pass the beginning of a character sequence to a function (as a pointer)
I want the function to count how often the passed pointer can be incremented
before it points to a '\0' character and return that number
I really see no need in allocating some memory dynamically in this.
--
Karl Heinz Buchegger