-2

I have the following function structure

int function(const char *str)
{
    return 0;
}

I never could fully understand why people use char *str rather than simply string str. So I am guessing this basically means that the argument is the pointer to the first character of the string. How do I determine the length of the string str given that argument?

What I've tried is to iterate through str, if I hit a NULL or "" or '', then that will be the end of it. However, none of these types are compatible for comparison. Please give me some clue regarding this. Thx!

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
return 0
  • 4,226
  • 6
  • 47
  • 72
  • possible duplicate of [get string size in bytes in c](http://stackoverflow.com/questions/15000544/get-string-size-in-bytes-in-c) – John Kugelman Oct 25 '14 at 19:50

3 Answers3

4

Jamesdlin's answer is good, but to answer your question about comparisons, you would use '\0', IE:

char* a = "a";
int size = 0;
while (a[size] != '\0')
    size++;

NULL is a pointer macro, "" is an empty character array (Though it has an implicit '\0', so you could theoretically do strcmp(a, "");), and '' is just an empty character, I'm not sure that it's even a valid statement.

Also, std::string is a C++ class and does not exist in the C standard library.

IllusiveBrian
  • 3,105
  • 2
  • 14
  • 17
3

In C, strings are typically NUL-terminated. For NUL-terminated strings, you can simply call strlen(str).

I never could fully understand why people use char *str rather than simply string str.

There is no string type in C. You could add a typedef:

typedef char* string;

But adding typedefs for pointer types is generally a bad idea (because now you need a separate typedef for const char*; const string would not be the same thing).

And while doing so might seem like a good idea, in practice it will obscure your code since char*/const char* for strings is the norm.

jamesdlin
  • 81,374
  • 13
  • 159
  • 204
0

You are almost correct, char *str is a pointer to the first character of a char array, but C has no predefined string type - it's just a zero-terminated char array. Instead of trying to write a function (although it would be a good student exercise), just call the library function in <string.h> with strlen (str); which takes a pointer to the character array. You don't pass *str or &str but just str if it is a declared array variable. If memory was allocated dynamically, you pass the allocated pointer, so if the pointer was declared as char *memstr you pass it as memstr. As others have said, it's best not to try to define a string, better to understand how the char array works.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56