我想用字符指针中的数据初始化一个字符数组。我为此编写了以下代码:
(请原谅我对结构所做的一切......实际上这段代码应该适合更大的东西,因此该结构及其使用的奇怪之处)
#include <iostream>
#include <string>
struct ABC
{
char a;
char b;
char c[16];
};
int main(int argc, char const *argv[])
{
struct ABC** abc;
std::string _r = "Ritwik";
const char* r = _r.c_str();
if (_r.length() <= sizeof((*abc)->c))
{
int padding = sizeof((*abc)->c) - _r.length();
std::cout<<"Size of `c` variable is : "<<sizeof((*abc)->c)<<std::endl;
std::cout<<"Value of padding is calculated to be : "<<padding<<std::endl;
char segment_listing[ sizeof((*abc)->c)];
std::cout<<"sizeof segment_listing is "<<sizeof(segment_listing)<<std::endl;
memcpy(segment_listing, r, _r.length());
memset( (segment_listing + _r.length()), ' ', padding);
std::cout<<segment_listing<<std::endl;
}
return 0;
}
但是,当我运行我的代码时,我会在字符串的末尾得到这些奇怪的字符:
(rh4dev01:~/rough) rghosh> ./crptr
Size of `c` variable is : 16
Value of padding is calculated to be : 10
sizeof segment_listing is 16
Ritwik °×
(rh4dev01:~/rough) rghosh> ./crptr
Size of `c` variable is : 16
Value of padding is calculated to be : 10
sizeof segment_listing is 16
Ritwik Ñ
(rh4dev01:~/rough) rghosh> ./crptr
Size of `c` variable is : 16
Value of padding is calculated to be : 10
sizeof segment_listing is 16
Ritwik g
(rh4dev01:~/rough) rghosh> ./crptr
Size of `c` variable is : 16
Value of padding is calculated to be : 10
sizeof segment_listing is 16
Ritwik pô
(rh4dev01:~/rough) rghosh> ./crptr
Size of `c` variable is : 16
Value of padding is calculated to be : 10
sizeof segment_listing is 16
Ritwik
(rh4dev01:~/rough) rghosh> ./crptr
Size of `c` variable is : 16
Value of padding is calculated to be : 10
sizeof segment_listing is 16
Ritwik àå
(rh4dev01:~/rough) rghosh> ./crptr
Size of `c` variable is : 16
Value of padding is calculated to be : 10
sizeof segment_listing is 16
Ritwik »
(rh4dev01:~/rough) rghosh> ./crptr
Size of `c` variable is : 16
Value of padding is calculated to be : 10
sizeof segment_listing is 16
Ritwik pZ
你能解释一下为什么会这样吗?因为我只打印一个字符数组,长度只有 16 个字符,不应该只打印 16 个字符吗?这两个(有时是零,有时是一个)字符来自哪里?
c
更重要的是,我是否通过填充 破坏了任何内存(不属于我的字符数组)?