C -> sizeof string is always 8

南楼画角 提交于 2019-11-27 09:23:40

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).

It is treating it as a pointer, the sizeof a pointer is obviously 8bytes = 64 bits on your machine

You say "don't worry about this -> lib i wrote" but this is the critical piece of information, as it defines string. Presumably string is char* and the size of that on your machine is 8. Thus, sizeof(given[i]) is 8 because given [i] is a string. Perhaps you want strlen rather than sizeof.

This is common mistake between the array of characters itself, and the pointer to where that array starts.

For instance the C-style string literal:

char hello[14] = "Hello, World!";

Is 14 bytes (13 for the message, and 1 for the null terminating character). You can use sizeof() to determine the size of a raw C-style string.

However, if we create a pointer to that string:

char* strptr = hello;

And attempt to find it's size with sizeof(), it will only always return the size of a data pointer on your system.

So, in other words, when you try to get the size of the string from a string library, you're truly only getting the size of the pointer to the start of that string. What you need to use is the strlen() function, which returns the size of the string in characters:

sizeof(strptr); //usually 4 or 8 bytes
strlen(strptr); //going to be 14 bytes

Hope this clears things up!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!