C/C++ 中的 sizeof char* 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12353973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:12:19  来源:igfitidea点击:

sizeof char* array in C/C++

c++csizeof

提问by Abalieno

There are plenty of similar inquires, but in my case I don't understand what isn't working:

有很多类似的查询,但就我而言,我不明白什么不起作用:

int mysize = 0;
mysize = sizeof(samplestring) / sizeof(*samplestring);
std::cout << mysize << '\n' << samplestring;

This outputs:

这输出:

4

Press 'q' to quit.

How is it possible? 4 definitely isn't the size of this string. I even tried the following, with the same result:

这怎么可能?4 绝对不是这个字符串的大小。我什至尝试了以下方法,结果相同:

mysize = sizeof(samplestring) / sizeof(samplestring[0]);

mysize = sizeof(samplestring) / sizeof(samplestring[0]);

EDIT: Ok, this is the declaration:

编辑:好的,这是声明:

char *samplestring = "Start."; 

I'm on C++, but I need to use functions that only accept char *. Later in the code I assign new strings to that variable, like:

我在使用 C++,但我需要使用只接受 char * 的函数。稍后在代码中,我将新字符串分配给该变量,例如:

samplestring = "Press 'r' for red text.";

Yes, the compiler gives me warnings, but I have no idea how can I use different strings if I can't overwrite them...

是的,编译器给了我警告,但是如果我不能覆盖它们,我不知道如何使用不同的字符串......

回答by Luchian Grigore

4isn't the size of the string, because samplestringisn't a string. It's a char*, whose size is (on your platform) 4, divided by 1 (size of char) is, correctly, 4.

4不是字符串的大小,因为samplestring不是字符串。它是一个char*,其大小为(在您的平台上)4,除以 1(的大小char),正确地为 4。

In C++, you'd use std::stringand the length()method.

在 C++ 中,您将使用std::stringlength()方法。

In C, you'd use strlenwhich takes as parameter a NULL-terminated char pointer.

在 C 中,您将使用strlenwhich 将 NULL 终止的字符指针作为参数。

回答by Praetorian

First of all, sizeof(samplestring[0])is the same as sizeof(*samplestring), they're both returning the size of the first element of the samplestringarray. And, assuming samplestringis an array of chars, sizeof(char)is defined to be 1.

首先,sizeof(samplestring[0])与 相同sizeof(*samplestring),它们都返回samplestring数组第一个元素的大小。并且,假设samplestring是一个字符数组,sizeof(char)定义为 1。

You haven't shown how samplestringis declared. It could be one of the following:

您还没有显示如何samplestring声明。它可能是以下之一:

char const *samplestring = "Hello, World!";

or

或者

char *samplestring = malloc( ... );

or

或者

char samplestring[10];

In the first 2 cases the type of samplestringis char *, so sizeof(samplestring)returns sizeof(char *), which, on your platform is 4.

在前两种情况下,类型samplestringchar *,因此sizeof(samplestring)返回sizeof(char *),在您的平台上为 4。

In the third case, the type of samplestringis char[10](array of 10 chars), but if you call a function that takes a char *as its parameter, the char array will decayto a pointer pointing to the first element of the array. In this case, trying to print sizeofwithin the function will still result in the size of a pointer being printed.

在第三种情况下,类型samplestringchar[10](10 个字符的数组),但是如果调用一个以 achar *作为参数的函数,字符数组将衰减为指向数组第一个元素的指针。在这种情况下,尝试sizeof在函数内打印仍然会导致打印指针的大小。

If you want the size of the original array to be printed from within the function, then the function parameter needs to be a pointer to the original array type (and the type includes size of the original array).

如果您希望从函数内部打印原始数组的大小,则函数参数需要是指向原始数组类型的指针(并且该类型包括原始数组的大小)。

#include <stdio.h>

void foo( char (*arr)[42] )
{
  printf( "%u", (unsigned)sizeof(*arr) );
}

int main()
{
  char arr[42];
  foo( &arr );

  return 0;
}  

Output:

输出:

42

This fixes the size of the array that can be passed to the function and is not desirable in a lot of cases. The only other solution is to keep track of the array yourself (or use strlenif you have a NULL terminated string).

这固定了可以传递给函数的数组的大小,在很多情况下是不可取的。唯一的其他解决方案是自己跟踪数组(strlen如果您有 NULL 终止的字符串,则使用)。

回答by Mark Ransom

There are two ways of making a string constant, and your technique only works on the first one. The first one makes an array of characters which you can get the size of at compile time, and the other creates a pointerto an array of characters.

有两种方法可以使字符串保持不变,您的技术仅适用于第一种。第一个创建一个字符数组,您可以在编译时获取其大小,另一个创建一个指向字符数组的指针

char samplestring[] = "hello";
char * samplestring = "hello";

Trying to take the size of the second case the way you're doing it just gives you the size of a pointer. On a 32-bit build the size of a pointer is 4 characters, i.e. a pointer takes the same amount of memory as 4 characters.

尝试按照您的方式获取第二种情况的大小只会为您提供指针的大小。在 32 位构建中,指针的大小为 4 个字符,即指针占用的内存量与 4 个字符相同。

The following will alwaysgive the correct length for a properly null-terminated string, but it's slower.

以下将始终为正确的以空字符结尾的字符串提供正确的长度,但速度较慢。

mysize = strlen(samplestring);

回答by Mike Seymour

It looks as though you have a pointer, not an array. Arrays are converted to pointers when the program requires it, so you'd get:

看起来好像你有一个指针,而不是一个数组。当程序需要时,数组被转换为指针,所以你会得到:

size_t size(char * p) { // p is a pointer
    return sizeof(p) / sizeof(*p); // size of pointer
}

size_t size(char p[]) { // p is also a pointer        
    return sizeof(p) / sizeof(*p); // size of pointer
}

although, since sizeof (char) == 1, the division is redundant here; if the pointer were to a larger type, then you'd get a differently unexpected result.

虽然,因为sizeof (char) == 1,这里的除法是多余的;如果指针指向更大的类型,那么您会得到不同的意外结果。

In C++ (but obviously not C), you can deduce the size of an array as a template parameter:

在 C++ 中(但显然不是 C),您可以推断出数组的大小作为模板参数:

template <typename T, size_t N>
size_t size(T (&)[N]) {
    return N;  // size of array
}

or you can use classes such as std::vectorand std::stringto keep track of the size.

或者您可以使用诸如std::vector和 之类的类std::string来跟踪大小。

In C, you can use strlento find the length of a zero-terminated string, but in most cases you'll need to keep track of array sizes yourself.

在 C 中,您可以使用strlen来查找以零结尾的字符串的长度,但在大多数情况下,您需要自己跟踪数组大小。

回答by Tristram Gr?bener

you are asking the size of a pointer on a char. So I guess you're using a 32bit system.

您正在询问字符上指针的大小。所以我猜你使用的是 32 位系统。

If you're using C++, use std::string :

如果您使用 C++,请使用 std::string :

std::string samplestring("Hello world");
std::cout << samplestring.size() << std::endl;

回答by Minion91

The sizeof of an element returns the size of the memory allocated for that object. In your example the string is probably declared somewhere as

元素的 sizeof 返回为该对象分配的内存大小。在您的示例中,字符串可能在某处声明为

samplestring[4]

In which case the size of the memory is 4. The method you probably want in your application is

在这种情况下,内存的大小为 4。您的应用程序中可能需要的方法是

strlen(samplestring);

Which returns the size of the null terminated string (without the termination)

它返回空终止字符串的大小(没有终止)