c++ copy string literal (from C) [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I want to save a C String to a C++ Variable. This shall than be passed to the C-API function.
The string is defined in the C-API
as
#define XI_PRM_BINNING_HORIZONTAL_MODE "binning_horizontal_mode"
I want to select the string in a switch
char * binnMode;
...
binnMode = XI_PRM_BINNING_HORIZONTAL_MODE;
But that fails because the C-literal is defined as char str[] (C++11)
I want to pass the string to a function that expects
xiSetParamInt(IN HANDLE hDevice, const char* prm, const int val)
How do I need to define binnMode in order to get this working?

Notice that the parameter is const char*, not char*.
That's convenient because it's also what binnMode needs to be.
String literals are immutable, and (in C++) const. Yours is a const char[<length+1>] (don't know where you heard it was a char[]) which decays nicely to a const char*.

Related

I can't trace this pointer to pointer array program [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
#include<iostream>
using namespace std;
char* str[]={"Man","Woman","Car","Plane",0};
int main(){
char** cp=str;
while(*cp!=0)
cout<<*cp++<<endl;
return 0;
}
It prints the String.
But when I print **cp++ I get only first letters like M,W,C,P.
For starters the array should be declared with the qualifier const because in C++ string literals have types of constant character arrays.
const char* str[]={"Man","Woman","Car","Plane",0};
In fact the declaration above is equivalent to
const char* str[]={ &"Man"[0], &"Woman"[0], &"Car"[0], &"Plane"[0], 0 };
because the string literals having array types used as initializers in this declaration are implicitly converted to pointers to their first elements.
In this declaration
char** cp=str;
that also should be written like
const char** cp=str;
the pointer cp points to the first element of the array that has the type char * and points to the first character of the string literal "Man".
Dereferencing the pointer cp one time like *cp you will get the first element of the array that has the pointer type char * and points to the character 'M' of the string literal "Man". Dereferencing the pointer the second time like **cp you will get an object of the type char that contain this character 'M'.

C++: strcpy non-ascii characters problem is possible? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am trying to create a specific case of a problem in my following code;
std::string id = "123456789123456789" // it can be different sized string too.
std::string my_id = "TEST_" + id;
char* temp_my_id = (char *) my_id.c_str();
strcpy(temp_my_id, my_id.c_str());
PRINT("my_id value : ", temp_my_id);
It is a legacy code in my project and I suspect the temp_my_id returns non-ascii character. Is this possible?
char* temp_my_id = (char *) my_id.c_str();
strcpy(temp_my_id, my_id.c_str());
source and destination can not have the same memory location in strcpy because both arguments are marked as restrict:
Bold test is mine:
restrict is a keyword (in C, not in C++) that can be used in pointer declarations. By
adding this type qualifier, a programmer hints to the compiler that
for the lifetime of the pointer, only the pointer itself or a value
directly derived from it (such as pointer + 1) will be used to access
the object to which it points.
you can try
char a[] = "123";
char *b = a;
strcpy(b, b);
returns:
warning: ‘strcpy’ source argument is the same as destination [-Wrestrict]
again in C, in C++ it is also broken because source and destination can not overlap.
strcpy does not really care about the encoding, it copies until it finds a NULL byte. So you just have to be careful that
the source ends with a zero byte and contains none in the middle
the source is not longer than the destination
source and destination should not overlap
see strcpy vs. memcpy and
http://www.cplusplus.com/reference/cstring/strcpy/

Create array of pointers in C++ [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I'm new comer to C++, so I'm very confused about the code below:
const char* headers[]= {"apple","pear","tree"};
So is this line supposed to create "an array of pointers to char"? (Maybe i'm wrong). If so, why such array of pointers being assigned to an array of strings?
Also I'm confused why bother to have such pointer array? Can't we simply do sth like: int array [5] = { 1, 2, 3, 4, 5 };
All such pointer/reference stuff in C++ are so confusing and difficult for people like me from Java world.
Many thanks!
Hope this will help, here is a basic explanation of what the line means with some crude illustrations.
Please note that all addresses are made up, and some things are simplified in hopes of making the concept easier to see. Forgive the crude art, I am far from an artist!
const char* headers[]= {"apple","pear","tree"};
This line is telling the compiler that you would like to allocate an array. The elements in the array will be of type char*. The const keyword tells the compiler that the object or variable is not modifiable. char* is the type of elements in the array. headers is the variable name, and the brackets [] indicate that headers is an array. The rest of the line is an initializer for the array. header will have 3 elements of type char* which basically means “pointer to a string of characters”.
The compiler will also allocate memory and initialize the array by filling it with each of the 3 strings in the braces {"apple","pear","tree"}
The first element in the header array header[0] will contain a pointer to the memory where the string “apple” is located.
The second element in the header array header1 will contain a pointer to the memory where the string “pear” is located.
const char* headers[]= {"apple","pear","tree"};
"If so, why such array of pointers being assigned to an array of strings?"
Because in C there is no such thing as a string. There is instead a sequence of characters with a trailing 0 at the end.
C++ has std::string.
const char* headers[]= {"apple","pear","tree"};
means headers is an array of char pointers. Simple way to dissect it to look at non array version
const char * fruit = "pear";
This creates a literal "pear\0" (note the 0 added on the end) and then creates a variable that points to the 'p' character. Ie it contains the address of where that 'p' is stored. Now back to
const char* headers[]= {"apple","pear","tree"};
This creates 3 literals 'apple\0', 'pear\0', 'tree\0'
It create a 3 entry array of char * pointers
It sets header[0] to point to the 'a' of apple
It sets header[1] to point to the 'p' of pear
It sets header[2] to point to the 't' of tree
Answering the question as asked:
const char* headers[]= {"apple","pear","tree"};
This line defines a variable named headers, with type "array of 3 pointers to const char" (where 3 is deduced from the number of initializers). The pointers are set to point to 3 string literals, which they remain immutable during program execution.

Using char and char[] in C++ [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm having trouble using type char. When I initialize my ID and Name in my struct by a constructor, why am I getting this error message? "expression must be a modifiable lvalue".
struct Staff
{
char ID[8];
char Name[30];
Staff()
{
ID = "";
Name = "";
}
};
Since this question is tagged C++ and the code make uses of C++ only features (such as constructors), I'm going assume you have mistakenly confused C with C++ in your title.
Don't use char arrays when you really mean strings. Use std::string instead:
struct Staff {
std::string ID;
std::string Name;
};
In this way the default constructor will behave as expected and you won't even need to specify it. The only additional line you'll need is the one that includes the necessary header:
#include <string>
on the very top of the file.
char in C and C++ is just another numeric type, like int, but smaller (generally one byte). An array of chars is not special -- it's basically a raw hunk of memory. A string literal is internally an array of chars as well, but C++ has no built-in support for copying arrays with operator= -- you have to copy the bytes yourself, for example via the (deprecated) strcpy C function (include cstring).
In C++, the usual way to deal with strings is to use std::string (include string), which is a class that wraps the string's bytes for you, and implements string copying, comparison, etc. in a clean, intuitive fashion.
You're also missing a semicolon at the end of the Staff structure, which will cause some interesting compile errors :-)
You cannot change the value of ID or Name since it is an array, not a pointer.
Either declare it as char pointer (in this case it's better to declare it as const char*):
const char *ID;
const char *Name;
Or use memset:
memset(ID, '\0', sizeof(ID));
memset(Name, '\0', sizeof(Name));
This will "initialize" your char arrays.
You can do the same to assign a string to the array using strncpy
strncpy(Name, "John Doe", sizeof(Name)-1);
The -1 accounts for the null terminating character.
What you need to do is
struct Staff
{
char ID[8];
char Name[30];
Staff() :
ID{0}, // Null terminate the array same as, ID[0] = 0;
Name{0} // Null terminate the array same as, Name[0] = 0;
{
}
};

how to convert std::string pointer to std::string [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
i have std::string pointer and i like to copy its value to ordinary std::string
i can't find quick and fast way to do it .
i have this :
int main ()
{
std::string * pStr = new std::string("hello")
std::string strNew = pStr->??? // how to convert ?
return 0;
}
Dereference:
std::string strNew = *pStr;
Two ways:
std::string strNew = pStr->c_str(); // Be careful of `\0` with in the string
or
std::string strNew = *pStr;
The second is better, because C-style string can not represent std::string correctly. It ends a string at first \0 and ignores trailing.