I have this code that produces an unexpected result for a char pointer:
#include <iostream>
#include <stdlib.h>
#include <string>
void main(int argv, char* argc[]) {
char* test1 = new char[7];
test1[0] = 'H';
test1[1] = 'a';
test1[2] = 'l';
test1[3] = 'e';
test1[4] = 't';
test1[5] = 'y';
test1[6] = 'a';
char* t2 = &test1[3];
std::cout << *t2 << std::endl;
std::cout << t2 << std::endl;
std::cout << std::endl;
int v[] = { 1,2,3,4 };
int* v2 = &v[0];
std::cout << *v2 << std::endl;
std::cout << v2 << std::endl;
std::cout << std::endl;
float f[] = { 0.2, 0.4, 0.6 };
float* f2 = &f[1];
std::cout << *f2 << std::endl;
std::cout << f2 << std::endl;
std::cout << std::endl;
std::string str = "A_string";
std::string *str2 = &str;
std::cout << *str2 << std::endl;
std::cout << str2 << std::endl;
std::cout << std::endl;
std::cin.ignore();
}
The output for this is variable but usually something like this:
What's going on? For the int, float, and string, printing the address prints the pointer address and printing the pointer prints the correct value. However, for the char array, while printing the pointer also prints the correct value, printing the address prints the last 4 elements of the array and a bunch of crap that varies per run.
Is there something about char that causes this or do I just have a funky setup? I've tried initializing the char array with brackets but it's the same result.
Never mind. I guess the solution is this:
std::cout << *t2 << std::endl;
std::cout << (void*)t2 << std::endl;
std::cout << std::endl;
Also found:
Why is address of char data not displayed?
Related
In c: Given the following code
int a;
char word[]=<some string>
Is there a difference between?
a = atoi(word)
a = atof(word)
atoi returns integer type, atof returns double.
So in the atof scenario you are additionally converting the temporary double into your int
Yes, you can.
But the compiler will emit warnings. See below:
It tells you what will happen.
All double or float values will be truncated (not rounded).
See the below code:
#include <iostream>
#include <cstdlib>
int main() {
int i1{};
int i2{};
int i3{};
char s1[] = "42";
char s2[] = "42.1";
char s3[] = "42.9";
i1 = std::atof(s1);
i2 = std::atof(s2);
i3 = std::atof(s3);
std::cout << s1 << "\t--> " << i1 << '\n'
<< s2 << "\t--> " << i2 << '\n'
<< s3 << "\t--> " << i3 << '\n';
}
If you want to get rid of the warnings and be more clean, you need to add a cast statement. Like below:
#include <iostream>
#include <cstdlib>
int main() {
int i1{};
int i2{};
int i3{};
char s1[] = "42";
char s2[] = "42.1";
char s3[] = "42.9";
i1 = static_cast<int>(std::atof(s1));
i2 = static_cast<int>(std::atof(s2));
i3 = static_cast<int>(std::atof(s3));
std::cout << s1 << "\t--> " << i1 << '\n'
<< s2 << "\t--> " << i2 << '\n'
<< s3 << "\t--> " << i3 << '\n';
}
There will be no compiler warning:
Program output will be:
I'm having an extremely frustrating time trying to get the Boost regex library to behave itself in XCode 8.
I've finally managed to sort the includes out, now I'm hitting compiler errors when attempting to run the following regex example from Boost's library documentation here.
The code is as follows:
void print_captures(const std::string& regx, const std::string& text)
{
boost::regex e(regx);
boost::smatch what;
std::cout << "Expression: \"" << regx << "\"\n";
std::cout << "Text: \"" << text << "\"\n";
if(boost::regex_match(text, what, e, boost::match_extra))
{
unsigned i, j;
std::cout << "** Match found **\n Sub-Expressions:\n";
for(i = 0; i < what.size(); ++i)
std::cout << " $" << i << " = \"" << what[i] << "\"\n";
std::cout << " Captures:\n";
for(i = 0; i < what.size(); ++i)
// compiler error in line above
{
std::cout << " $" << i << " = {";
for(j = 0; j < what.captures(i).size(); ++j)
// compiler erro in line above
{
if(j)
std::cout << ", ";
else
std::cout << " ";
std::cout << "\"" << what.captures(i)[j] << "\"";
}
std::cout << " }\n";
}
}
else
{
std::cout << "** No Match found **\n";
}
}
int main(int , char* [])
{
print_captures("(([[:lower:]]+)|([[:upper:]]+))+", "aBBcccDDDDDeeeeeeee");
print_captures("(.*)bar|(.*)bah", "abcbar");
print_captures("(.*)bar|(.*)bah", "abcbah");
print_captures("^(?:(\\w+)|(?>\\W+))*$",
"now is the time for all good men to come to the aid of the party");
return 0;
}
I'm getting two errors at the points indicated in the block above that both read:
No member named 'captures' in 'boost::match_results<std::__1::__wrap_iter<const char *>, std::__1::allocator<boost::sub_match<std::__1::__wrap_iter<const char *> > > >'
Apologies in advance if this question has been answered elsewhere.
Any idea how I can fix this?
I'm attempting to pass a character array located in _name into a char reference called name.
However, when passing the array pointer into the reference, it would ONLY display the first character rather than the whole string.
My question is how would you create a Character reference array to copy the original pointer into it then displaying it? As show in item.cpp we copy _name pointer into reference of name then return name, it however only displays the first character of the string.
I will only show the relevant pieces of my code.
Item.cpp:
void Item::name(const char * name){
strncpy(_name, name , 20);
}
const char& Item::name() const{
char& name = *_name;
return name;
}
ItemTester.cpp:
Main():
int main(){
double res, val = 0.0;
fstream F;
SItem Empty;
SItem A("456", "AItem", 200);
SItem B("567", "BItem", 300, false);
//cout << A.name() << endl;
B.quantity(50);
//cout << Empty << endl;
cout << A << endl << B << endl << endl;
cout << "Enter Item info for A: (Enter 123 for sku)" << endl;
cin >> A;
cout << "Copying A in C ----" << endl;
SItem C = A;
cout << C << endl << endl;
cout << "Saving A---------" << endl;
A.save(F);
cout << "Loading B----------" << endl;
B.load(F);
cout << "A: ----------" << endl;
cout << A << endl << endl;
cout << "B: ----------" << endl;
cout << B << endl << endl;
cout << "C=B; op=----------" << endl;
C = B;
cout << C << endl << endl;;
cout << "Operator ==----------" << endl;
cout << "op== is " << ((A == "123") && !(A == "234") ? "OK" : "NOT OK") << endl << endl;
cout << "op+=: A += 20----------" << endl;
A += 20;
cout << A << endl << endl;
cout << "op-=: A -= 10----------" << endl;
A -= 10;
cout << A << endl << endl;
cout << "op+=double: ----------" << endl;
res = val += A;
cout << res << "=" << val << endl << endl;
return 0;
}
ostream write
virtual std::ostream& write(std::ostream& os, bool linear)const{
return os << sku() << ": " << name() << endl
<< "Qty: " << quantity() << endl
<< "Cost (price * tax): " << fixed << setprecision(2) << cost();
}
Let me know if i missed any important details and il edit my post with it.
char& is reference to char, thus just a single character. Reference to array of characters would be char*&.
Example:
class Test
{
private:
static const size_t maxlen = 100;
char* _name;
public:
Test() : _name(new char[maxlen+1]) {}
~Test() {delete _name;}
void name(const char* s)
{
if(strlen(s) >= maxlen)
throw "too long";
else
{
memcpy(_name, s, strlen(s) * sizeof(char));
_name[strlen(s)] = '\0';
}
}
char*& name()
{
return _name;
}
};
int main()
{
Test obj;
obj.name("testname");
cout<<"Name = "<<obj.name()<<endl;
obj.name()[0] = '*';
cout<<"After change: Name = "<<obj.name()<<endl;
return 0;
}
EDIT:
I would change "getter" to something like:
char*& Item::name() {
return _name;
}
Actually if you do want the method to be "const", in the sense that user of the class should not change the elements of the array, or the actual address of the array, then you need not return a char*&, you can simply return const char*
const char* Item::name() const {
return _name;
}
As far as I see, the purpose of a char*& type is that the client would be able to change the actual address of an address.
As CForPhone pointed out, char& is not really what you want, you probably meant char*. But even then, using char* to represent strings is for C. In C++, you should use std::string:
const string Item::name() const{
string name(_name);
return name;
}
I want to repetitively solve the CG/BicGSTAB using CUSP solver, called from Fortran. To avoid transfers I am passing the Fortran data directly to CUSP. The code compiles but breaks at the run time flagging:
terminate called after throwing an instance of 'thrust::system::system_error'
what(): invalid argument
terminate called recursively
Aborted (core dumped)
Let alone the core of the code, even the print stream is not happening. The code of course is in the preliminary stage, but I wonder what is wrong with it.
extern "C" void bicgstab_(int *device_I, int *device_J, float *device_V, float *device_x, float *device_b, int *n, int *nnz){
int N = *n;
int NNZ = *nnz;
std::cout << N << " " << NNZ << " " << *device_I << std::endl;
for(int i=0; i<N;i++)std::cout << device_I[i] << " "; std::cout << std::endl;
for(int i=0; i<NNZ;i++)std::cout << device_J[i] << " "; std::cout << std::endl;
for(int i=0; i<NNZ;i++)std::cout << device_V[i] << " "; std::cout << std::endl;
for(int i=0; i<N;i++)std::cout << device_x[i] << " "; std::cout << std::endl;
for(int i=0; i<N;i++)std::cout << device_b[i] << " "; std::cout << std::endl;
// *NOTE* raw pointers must be wrapped with thrust::device_ptr!
thrust::device_ptr<int> wrapped_device_I(device_I);
thrust::device_ptr<int> wrapped_device_J(device_J);
thrust::device_ptr<float> wrapped_device_V(device_V);
thrust::device_ptr<float> wrapped_device_x(device_x);
thrust::device_ptr<float> wrapped_device_b(device_b);
// use array1d_view to wrap the individual arrays
typedef typename cusp::array1d_view< thrust::device_ptr<int> > DeviceIndexArrayView;
typedef typename cusp::array1d_view< thrust::device_ptr<float> > DeviceValueArrayView;
std::cout << wrapped_device_I[3];
/*
DeviceIndexArrayView row_indices (wrapped_device_I, wrapped_device_I + (N+1));
DeviceIndexArrayView column_indices(wrapped_device_J, wrapped_device_J + NNZ);
DeviceValueArrayView values (wrapped_device_V, wrapped_device_V + NNZ);
DeviceValueArrayView x (wrapped_device_x, wrapped_device_x + N);
DeviceValueArrayView b (wrapped_device_b, wrapped_device_b + N);
// std::cout << device_x[0] ;
// for(int i=0;i<NNZ;i++)std::cout << column_indices[i] << std::endl;
// combine the three array1d_views into a csr_matrix_view
typedef cusp::csr_matrix_view<DeviceIndexArrayView,
DeviceIndexArrayView,
DeviceValueArrayView> DeviceView;
// construct a csr_matrix_view from the array1d_views
DeviceView A(N, N, NNZ, row_indices, column_indices, values);
// set stopping criteria: // iteration_limit = 100 // relative_tolerance = 1e-5
cusp::verbose_monitor<float> monitor(b, 100, 1e-5);
// solve the linear system A * x = b with the Conjugate Gradient method
// cusp::krylov::bicgstab(A, x, b);*/
}
If this is not feasible, I can move over to another approach,but as I am not sure about the correctness, I am unable to decide. Any help is appreciated.
I have two bytes, 8 bit octets, which should be read as: [3 bits][4 bits][3 bits].
Example:
unsigned char octet1 = 0b11111111; // binary values
unsigned char octet2 = 0b00000011;
As integers: [7][15][7].
Anybody can give me a hint where to start?
In a kind of pseudocode
octet1 = 0b11111111
octet2 = 0b00000011
word = octet1 | octet2<<8
n1 = word & 0b111
n2 = word>>3 & 0b1111
n3 = word>>7 & 0b111
Hi here is a method that is tested and compiled using VC++9
#pragma pack( 1 )
union
{
struct
{
unsigned short val1:3;
unsigned short val2:4;
unsigned short val3:3;
unsigned short val4:6;
} vals;
struct
{
unsigned char octet1:8;
unsigned char octet2:8;
} octets;
short oneVal;
} u = {0xFFFF};
unsigned char octet1 = 0xFF; //1 1111 111
unsigned char octet2 = 0x03; //000000 11
//000000 111 1111 111 0 7 15 7
u.octets.octet1 = octet1;
u.octets.octet2 = octet2;
cout << "size of u.vals:" << sizeof(u.vals)<< endl;
cout << "size of u.octets:" << sizeof(u.octets)<< endl;
cout << "size of u.oneVal:" << sizeof(u.oneVal)<< endl;
cout << "size of u:" << sizeof(u)<< endl;
cout << endl;
cout << "Your values:" << endl;
cout << "oneVal in Hex: 0x";
cout.fill( '0' );
cout.width( 4 );
cout<< hex << uppercase << u.oneVal << endl;
cout << "val1: " << (int)u.vals.val1 << endl;
cout << "val2: " << (int)u.vals.val2 << endl;
cout << "val3: " << (int)u.vals.val3 << endl;
cout << "val4: " << (int)u.vals.val4 << endl;
cout << endl;
octet1 = 0xCC; //1 1001 100
octet2 = 0xFA; //111110 10
//111110 101 1001 100 62 5 9 4
u.octets.octet1 = octet1;
u.octets.octet2 = octet2;
cout << "Some other values:" << endl;
cout << "oneVal in Hex: 0x";
cout.fill( '0' );
cout.width( 4 );
cout<< hex << uppercase << u.oneVal << endl;
cout << dec;
cout << "val1: " << (int)u.vals.val1 << endl;
cout << "val2: " << (int)u.vals.val2 << endl;
cout << "val3: " << (int)u.vals.val3 << endl;
cout << "val4: " << (int)u.vals.val4 << endl;
cout << endl;
octet1 = 0xCC; //1 1001 100
octet2 = 0xFA; //111110 10
//111110 101 1001 100 62 5 9 4
u.oneVal = ( (( unsigned short )octet2 ) << 8 ) | ( unsigned short )octet1;
cout << "Some thing diffrent asignment:" << endl;
cout << "oneVal in Hex: 0x";
cout.fill( '0' );
cout.width( 4 );
cout<< hex << uppercase << u.oneVal << endl;
cout << dec;
cout << "val1: " << (int)u.vals.val1 << endl;
cout << "val2: " << (int)u.vals.val2 << endl;
cout << "val3: " << (int)u.vals.val3 << endl;
cout << "val4: " << (int)u.vals.val4 << endl;
cout << endl;
Also note that I uses #pragma pack( 1 ) to set the structure packing to 1 byte.
I also included a way of assigning the two octets into the one short value. Did this using bitwise shift "<<" and bitwise or "|"
You can simplify the access to u by dropping the named structures. But I wanted to show the sizes that is used for the structures.
Like this:
union
{
struct
{
unsigned short val1:3;
unsigned short val2:4;
unsigned short val3:3;
unsigned short val4:6;
};
struct
{
unsigned char octet1:8;
unsigned char octet2:8;
};
short oneVal;
} u = {0xFFFF};
Access would now be as simple as
u.oneVal = 0xFACC;
or
u.octet1 = 0xCC;
u.octet2 = 0xFA;
you can also drop either oneVal or octet1 and octet2 depending on what access method you like.
No need to put the two bytes together before extracting bits we want.
#include <stdio.h>
main()
{
unsigned char octet1 = 0b11111111;
unsigned char octet2 = 0b00000011;
unsigned char n1 = octet1 & 0b111;
unsigned char n2 = (octet1 >> 3) & 0b1111;
unsigned char n3 = (octet1 >> 7) | (octet2 + octet2);
printf("octet1=%u octet2=%u n1=%u n2=%u n3=%u\n",
octet1, octet2, n1, n2, n3);
}
oct2| oct1
000011|1 1111 111
---- ---- ---
7 0xf 7
Just a hint,(assuming it is homework)
Note: 0x11111111 doesn't mean 8 bits all set to 1. It's an hexadecimal number of 4 bytes, where any byte is set to 0x11.
0xFF is a single byte (8 bit) where any bit is set to 1.
Then, to achieve what you want you could use some MACROs to isolate the bits you need:
#define TOKEN1(x) ((x)>>7)
#define TOKEN2(x) ( ((x)>>3) & (0xFF>>5) )
#define TOKEN3(x) ( ((x)>>5) & (0xFF>>5) )
Didn't test it.
Another idea, could be that of putting in an union a char and a struct using bitfield chars
union {
struct { char a:3; char b:4; char c:3; };
char x;
};
This way you can use x to edit the whole octet, and a, b and c to access to the single tokens...
Edit: 3+4+3 != 8.
If you need 10 bits you should use a short instead of a char. If, instead, some of those bits are overlapping, the solution using MACRO will probably be easier: you'll need more than one struct inside the union to achieve the same result with the second solution...
You can use boolean opeations to get and set the individual values.
It's unclear which bits of your octets apply to which values but you only need & (bitwise AND), | (bitwise OR), << (left shift) and >> (right shift) to do this.
Start from writing a packing/unpacking functions for your 2-byte hybrids.
If you so the work with C/C++ - you may use the intrinsic support for this:
struct Int3 {
int a : 3;
int b : 4;
int c : 3;
};
Bitfields could be one option. You may need to pad your struct to get the bits to line up the way you want them to.
Refer to Bitfields in C++ or search StackOverflow for C++ and bitfields or you can use bitwise operators as outline in the other answers.
Do you mean, if we "concatenate" octets as octet2.octet1, we will get 000000[111][1111][111]?
Then you may use bit operations:
">>" and "<<" to shift bits in your value,
"&" to mask bits
"+" to combine values
For example, "middle" value (which is 4-bits-length) may be received in the following way:
middle = 15 & (octet1 >> 3);
assert(CHAR_BIT == 8);
unsigned int twooctets = (octet2 << 8) | (octet1); /* thanks, Jonas */
unsigned int bits0to2 = (twooctets & /* 0b0000_0000_0111 */ 0x007) >> 0;
unsigned int bits3to6 = (twooctets & /* 0b0000_0111_1000 */ 0x078) >> 3;
unsigned int bits7to9 = (twooctets & /* 0b0011_1000_0000 */ 0x380) >> 7;