문자 배열의 데이터로 문자 배열을 초기화하고 싶습니다. 나는 이것에 대한 다음과 같은 코드를 작성 :memset 및 memcpy를 올바르게 사용하여 C++에서 문자 배열을 초기화하십시오.
(친절 실제로이 코드는 따라서 더 큰 뭔가 그 구조와 그 사용의 기묘에 맞게 예정이다 .. 나는 구조와 모두와 함께하고있는 무슨 변명) 그 일이 왜(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
당신이 설명해 주시겠습니까 : 내 코드를 실행하면
#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;
}
그러나, 나는 나의 문자열의 끝이 이상한 문자를 얻을? 문자 배열 만 인쇄하기 때문에 길이는 16 문자 뿐이므로 16 문자 만 인쇄하면 안 됩니 까? 그 두 명 (때로는 제로 가끔은 하나의 문자)이 어디에서 오는가?
더 중요한 것은, 내 패딩에 의해 (내 문자 배열 c
)에 속하지 않은 메모리가 손상 되었습니까?
에는 널 문자 없다 (차이가있다). 'memcpy','memset' 또는 c-style 배열을 사용하는 정확한 방법은 전혀 아닐 것입니다. 너는 무엇을 달성하려고하는 것 외에? – Grizzly
@JohnDibling 그것은 c와 C++를 혼합하기 때문에 무서운가? – Chani
표준은 구현을 위해 전역 네임 스페이스에서 밑줄로 시작하는 이름을 예약하기 때문에'_r'은 이름에 나쁜 생각입니다. –