Need to understand this question

Hi,
First of all sorry for indirect/inexact title of this post. (I wrote it like that intentionally for a reason)

Now coming to the business, there is a question given to me as an assignment, which I have some idea but I can't understand it completely. What I just want from you is a hint or two about how to implement it.

Here's the question: -

Write two versions of function "strlen". The first version should use array subscripting, and the second version should use pointers and pointer arithmetic.
The output should be like this:-

Enter a string: howLongCanThisNameWithoutQuestionPossiblyBe?

According to stringLength1 the string length is: 44
According to stringLength2 the string length is: 44


Now what I'm guessing so far is:-

1 - The first version should use array subscripting,

This means means I have to define a char array, input a string from user and output its length using strlen. Right?

2 - the second version should use pointers and pointer arithmetic

Does this mean that I have to use character type pointer array? And about the pointer arithmetic., I have no idea.

So if anyone can give me a hint, it would be appreciated.

P.S. I am not asking for a solution or complete code, so go easy on my post. :)
Last edited on
Hrm... I replied to this but my reply seems to have gotten swallowed by the boards.


Anyway... you are not supposed to use strlen at all. You are supposed to write your own functions which do the same job as strlen.

Specifically... you need to write 2 functions:

1) One which uses the array subscript operator (aka, the [bracket] operator) to access characters in the string.
Example: foo[x]

2) One which uses pointer math and the indirection operator to access characters in the string.
Example: *(foo + x)
Last edited on
Oh, thanks Disch. That really helped me understand it. And BTW about that second part, is that a pointer to an array like *foo[x]? Or, is it a different type of pointer implementation?
is that a pointer to an array like *foo[x]?


No.

The 2nd version should not use the [brackets] at all. It should only use pointer math (+) and pointer indirecton (*)


Remember that the [bracket] operator is really just shorthand for pointer math.

That is: foo[x] is functionally identical to *(foo + x)


EDIT: My previous summary might be too simplistic. Pointer math might also include the ++ operator or the += operator depending on how you want to do it.
Last edited on
Thank you very much Disch, your explanation really helped. :)
Last edited on
happy to help. =)
Topic archived. No new replies allowed.