Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
660 views
in Technique[技术] by (71.8m points)

C -> sizeof string is always 8

#include "usefunc.h" //don't worry about this -> lib I wrote
int main()
{
  int i;
  string given[4000], longest = "a"; //declared new typdef. equivalent to 2D char array
  given[0] = "a";
  printf("Please enter words separated by RETs...
");
  for (i = 1; i < 4000 && !StringEqual(given[i-1], "end"); i++)
    {
      given[i] = GetLine();
      /*
      if (sizeof(given[i]) > sizeof(longest))
    {
      longest = given[i];
    }
      */
      printf("%lu
", sizeof(given[i])); //this ALWAYS RETURNS EIGHT!!!
    }
  printf("%s", longest);
}

Why does it always return 8???

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is no string data type in C. Is this C++? Or is string a typedef?

Assuming string is a typedef for char *, what you probably want is strlen, not sizeof. The 8 that you are getting with sizeof is actually the size of the pointer (to the first character in the string).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...