C/C ++中的sizeof char *数组 [英] sizeof char* array in C/C++

查看:62
本文介绍了C/C ++中的sizeof char *数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多类似的查询,但就我而言,我不明白什么是行不通的:

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;

这将输出:

4

Press 'q' to quit.

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

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

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

好的,这是声明:

char *samplestring = "Start."; 

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

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:

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

推荐答案

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

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

在C ++中,您将使用 std :: string length()方法.

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

在C语言中,您将使用 strlen ,它将以NULL终止的char指针作为参数.

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

这篇关于C/C ++中的sizeof char *数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆