2
size_t stringlength(const char *s) 

Using this function, how could find the length of a string? I am not referring to using strlen(), but creating it. Any help is greatly appreciated.

2
  • 3
    Iterate over s until you reach the 0-terminator, increment counter on the way. Commented Jul 9, 2012 at 13:16
  • 2
    Increment count from 0 until current char is '\0' Commented Jul 9, 2012 at 13:17

4 Answers 4

10

Cycle/iterate through the string, keeping a count. When you hit \0, you have reached the end of your string.

The basic concepts involved are a loop, a conditional (to test for the end of string), maintaining a counter and accessing elements in a sequence of characters.

Note: There are more idiomatic/clever solution. However OP is clearly new to C and programming (no offense intended, we all started out as newbies), so to inflict pointer arithmetic on them as one of solutions did or write perhaps overly terse/compact solutions is less about OP's needs and more about a demonstration of the posters' programming skills :) Intentionally providing suggestions for a simple-to-understand solution earned me at least one downvote (yes, this for "imaginary code" that I didn't even provide. I didn't want to ready-serve a code solution, but let OP figure it out with some guidance).

Main Point: I think answers should always be adjusted to the level the questioner.

Sign up to request clarification or add additional context in comments.

9 Comments

Thank you. I understand the ideas behind it, but what about the code? Sorry, I'm just a little lost!
@LucySmith: I thought you want to implement it.
@Downvoter Why the downvote? Is it because I didn't provide code? I thin there's sufficient information for OP to implement this on her own. A downvote w/o explanation doesn't help OP, SO or me.
@RudyVelthuis Yes, I understand about the extra variable. Re "not harder to understand" .. agreed, not for someone already familiar with idiomatic C and pointers, I don't think that applies to OP given the question. I try to adjust my answers to the level of the OP. I was just curious about the downvote (I'm over my points for the day already, so the 2 points don't matter). However, I would never downvote a functional solution (esp one that's meant to be helpful) based on style.
I don't think it is harder to understand in general, no matter on which level one is. I expect people to understand a simple subtraction.
|
2
size_t stringlength(const char *s) { size_t count = 0; while (*(s++) != '\0') count++; return count; } 

The confusing part could be the expression *(s++), here you're moving the pointer to point the next character in the buffer using the ++ operator, then you're using the dereferencing operator * to get the content at the pointer position. Another more legible approach would be:

size_t stringlength(const char *s) { size_t count = 0; while (s[count] != '\0') count++; return count; } 

Another couple of reference versions (but less legible) are:

size_t stringlength(const char *s) { size_t count = 0; while (*s++) count++; return count; } size_t stringlength(const char *s) { const char* c = s; for (; *c; c++); return c - s; } 

Although the code stated here is just a reference to give you ideas of how to implement the algorithm described in the above answer, there exists more efficient ways of doing the same requirement (check the glibc implementation for example, that checks 4 bytes at a time)

5 Comments

If you're going make this a public API, make sure you check for a valid pointer. if (s == __nullptr).
I didn't downvote, but perhaps given OP's question, the answer is a bit too idiomatic? I.e, it might be helpful to have a less "terse" version of the code also to help communicate the ideas behind the code?
IMHO: making if (s == NULL) return 0; Can mask some programming errors. The NULL have no length. NULL is "nothing". So, if a NULL pointer was passed,a segmentation fault the programmer will get it and fix it. Your first implementation is better. Also, I did not the downvote, maybe the reason for someone do this it's because you can fornece full code in thread tagged as homeworkd. You can help it by explaning how to do it yourself.
@Jack Yes, you're right, it should be a seg-fault, some bugs can be hidden. I just supplied code because she stated in the first answer that she didn't know how to start, so I give her a reference. This code is not the best way to do this (a better implementation should check 4 bytes per iteration as the glibc strlen does, is only a way that introduces some concepts that may not be familiar from a newbie perspective (pointer dereferencing, operator precedence, etc), in a more legible way that while(*p++) c++;, anyway thanks for the explanation
A typo in my previous comment: I did mean "you can 't fornece full code".. @h3nr1x, I understand. You wanted to write a legible code for a beginner in C programming. But as I mentioned before, your first implementation, where you don't use arithmetic pointer expressions applies to this concept.
0

This might not be a relevant code, But I think it worth to know. Since it saves time...

int a[] = {1,2,3,4,5,6}; unsigned int i,j; i = &a; //returns first address of the array say 100 j = &a+1; //returns last address of the array say 124 int size = (j-i)/sizeof(int); // (j-i) would be 24 and (24/4) would be 6 //assuming integer is of 4 bytes printf("Size of int array a is :%d\n",size); 

And for strings ::

char a[] = "Hello"; unsigned int i,j; j = &a+1; //returns last address of the array say 106 i = &a; //returns first address of the array say 100 printf("size of string a is : %d\n",(j-i)-1); // (j-i) would be 6 

If you are confused how come &a+1 returns the last address of the array, check this link.


Comments

-1

Assuming s is a non-null pointer, the following function traverses s from its beginning until the terminating zero is found. For each character passed s++; count is incremented count++;.

size_t stringlength(const char *s) { size_t count = 0; while (*s) { s++; count++; } return count; } 

2 Comments

Don't to forget that's a homework question. Explain how to do it instead of only post full code.
While editing this, I kept the original intent of the example. However, in my world, this function should still have checked to see if s were null or not. In C (and quite a few other languages), it should not be assumed that a pointer is OK.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.