I wanted to initialize a character array with the data from a character pointer. I wrote the following code for this:
(kindly excuse what I am doing with the structure and all .. actually this code is supposed to fit into something bigger and hence the strangeness of that structure and its use)
#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;
}
However, when I run my code I get these wierd characters at the end of my string:
(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
Can you please explain why that is happening ? Since I am printing only a character array taht is only 16 characters in length, shouldn't only 16 characters get printed ? Where are those two (sometimes zero and sometimes one) characters coming from ?
More importantly, am I corrupting any memory (that does not belong to my character array c) by my padding ?
std::coutI assume your question is meant to be C++ and not C (There is a difference). The correct way to usememcpy,memsetor c-style arrays would be not at all. Besides what are you even trying to achieve?_ris a bad idea for a name because the standard reserves names beginning with underscores in the global namespace for the implementation.