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
From my understanding a string is just an array of char, so if i have a pointer reference to some char values shouldn't I be able to do:
*dest = "char"
However that doesn't work i have to do:
*dest = 'c';
*dest = 'h';
*dest = 'a';
*dest = 'r';
so if i have a pointer reference to some char values shouldn't I be able to do:
*dest = "char"
No, you shouldn't be able to do so.
*dest is a char. A single char object can only hold a single char object. A string is an array of characters. You cannot assign a string to a char.
However, if you had a pointer reference to some const char values, then you could assign the pointer like this:
dest = "char"
This would make the referred pointer to point to the string literal. However, this is different from *dest = 'c'; *dest = 'h'; .... The pointer assignment modifies the pointer and keeps the previously pointed characters unmodified, while assigning to the pointed character modifies the pointed characters, while keeping the pointer unmodified.
I'm guessing that by 'string' you ment a C-style string, so a char*
*dest = "char"
From what you said, dest is a char&*, when you dereference it, you get a char, type of "char" is const char*, so you're trying to assign a const char* to a char, which is a compile time error.
You should use std::string, which will enable you to do the assignment you described above, and also allocate and free memeory for you.
std::string dest = "char";
Related
This question already has answers here:
What happened when we do not include '\0' at the end of string in C?
(5 answers)
What is the difference between char s[] and char *s?
(14 answers)
Why do string literals (char*) in C++ have to be constants?
(2 answers)
Closed last year.
I am a C++ newbie. Although many similar questions have been asked and answered, I still find these concepts confusing.
I know
char c='a' // declare a single char c and assign value 'a' to it
char * str = "Test"; // declare a char pointer and pointing content str,
// thus the content can't be modified via point str
char str1[] = "Test"; // declare a char array str1 and assign "Test" to it
// thus str1 owns the data and can modify it
my first question is char * str creates a pointer, how does char * str = "Test"; work? assign a string literal to a pointer? It doesn't make sense to me although it is perfectly legal, I think we can only assign an address to a pointer, however "Test" is a string literal not an address.
Second question is how come the following code prints out "Test" twice in a row?
char str2[] = {'T','e','s','t'}; // is this line legal?
// intializing a char array with initilizer list, seems to be okay to me
cout<<str2<<endl; // prints out "TestTest"
why cout<<str2<<endl; prints out "TestTest"?
char * str = "Test"; is not allowed in C++. A string literal can only be pointed to by a pointer to const. You would need const char * str = "Test";.
If your compiler accepts char * str = "Test"; it is likely outdated. This conversion has not been allowed since C++11 (which came out over 10 years ago).
how does char * str = "Test"; work?
String literals are implicitly convertible to a pointer to the start of the literal. In C++ arrays are implicitly convertible to pointer to their first element. For example int x[10] is implicitly convertible to int*, the conversion results in &(x[0]). This applies to string literals, their type is a const array of characters (const char[]).
how come the following code prints out "Test" twice in a row?
In C++ most features related to character strings assume the string is null terminated, which is implied in string literals. You would need {'T','e','s','t','\0'} to be equivalent to "Test".
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 3 years ago.
Improve this question
I create a pointer to an array of pointers to char arrays (double ptr):
const char **strptr = new const char*[str_arr.size()]; //str_arr.size() = number of strings
I then try to dynamically allocate memory for each of the individual pointers to the strings:
for (int i=0; i < str_arr.size(); i++) {
size_t len = str_arr[i].length(); //length of each string
strptr[i] = new char[len+1]; //+1 for null character
strcpy(strptr[i], vars[i]->name().c_str()); // errors here
}
I then use the double pointer in functions, etc.
somefxn(strptr); ...
Then deallocate the memory:
for (int i=0; i< str_arr.size(); i++) { delete [] strptr[i]; }
delete [] strptr;
Seems like I've covered the necessary bases. But, I get these errors on the strcpy line:
"error: invalid conversion from 'const char*' to 'char*' ",
"error: initializing argument 1 of 'char* strcpy(char*, const char*)' "
Seems like a simple type issue, so I changed this line:
strptr[i] = new const char[len+1];
Same errors, and this new one on the strptr[i] line:
"error: uninitialized const in 'new' of 'const char' "
Not sure what to make of this. I think I'm overlooking a detail with the pointers and memory allocation, but haven't figure it out. Any ideas?
strcpy(strptr[i], vars[i]->name().c_str()); // errors here
Since you declared strptr as
const char **strptr = ...
The compiler does not allow you to change anything that strptr[i] points to. Remove the const.
char **strptr = ...
Unless you are required to use char** strptr for reasons beyond your control, you should switch to using std::string and std::vector.
std::vector<std::string> str_array;
That will obviate the need for writing a bunch of errorprone code.
const char **strptr = new const char*[5];
Is a non-const pointer to a non-const pointer to const char.
You can modify the double pointer by doing e.g. strptr++; or strptr=nullptr;.
You can modify the individual pointers like strptr[i]= new const char[2]{'a', 'b'}; or strptr[i]++;.
But you cannot modify the const char value i.e strptr[i][j]='b'; won't work.
std::strcpy tries to do just that and compiler rightfully complains of course.
Firstly, avoid using owning bare pointers. They are usually hardly ever needed. You appear to be allocating arrays. The simplest solution to allocate memory for an array is std::vector, or specifically for character strings, std::string.
The most efficient way of storing an array of arrays is a flat array containing all elements. In this case an appropriate solution is a single std::string. If you have a function that takes a const char ** as an argument, you can use an array of const char* pointers to offsets into that string container.
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 5 years ago.
Improve this question
I'm really confused about this because personally, I come from a java background, and recently began c++. So, I learnt all the basic stuff, like, printing stuff out to the screen and whatnot, and now, I learnt POINTERS. So, the person on youtube (The Cherno's C++ Pointer tutorial This was not the video where he declared the const char*, just the pointer tutorial that I followed.) I've been following was using this following statement to declare what I know as a 'string'.
const char* str = "random text here";
But, how is a char* converted into a string, and its even using the double quotation marks like a string! Also, what does a constant have to do with any of this? If I remove the const from my code it gives me an error. But, I understand what a pointer is. It is a variable that holds the memory address of another variable, so if one was to access that variable directly, they would just have to do *ptrVarName and dereferenced it. But how can a string "like this one" be a memory address?
Wouldn't I have to do something like this?
char[] str = "string here";
and THEN do:
char* stringPointer = *str;
(WARNING: untested code!)
Thanks in advance.
(oh and sorry if this is a really NOOBY question or the question is poorly constructed, I've just started out with c++ and stackoverflow)
EDIT: Ok, so I understand what the char* str means. It means that when you reference *str, it means that you're accessing the first character in memory. Ok, I get it now. But, what does const mean?
const char* str = "random text here";
On the right hand side, the "random text here" defines a string literal which actually is an array of type const char[17] (including the null terminator character). When you assign that array to const char* str it decays to a pointer that points to the first character. You cannot modify the string literal through the pointer because string literals are stored in read-only memory, so the following would be illegal: str[0] = 'x';
char[] str = "string here";
This one is different. It defines the char array str which has the same size as the string literal on the right hand side (const char[12]). The string literal will be copied into the array str, so you will be able to modify str. In this case, it would be legal to write str[0] = 'x';.
If you declare const char* sth ="mystring"
It will place mystring inthe memory and sth pointing to that its work like array but with direct access to memory
These are plain C-strings. A C string is always null terminated. In other words- it has '\0' at the end. So you need only the place in memory where the string starts and you can find when it ends.
For pointer arithmetic these [] brackets are only syntax sugar. str[] is the same as *str and str[1] is the same as *(str+1) only incrementing the pointer by one char (8 bits) and getting the address of the second element.
C doesn't really have strings. A string is an array of characters, terminated by a nul (0). Now arrays and pointers in C are closely linked, and a char * or const char * usually points to a string, but only in the same way as other pointers usually point to arrays. An individual char * might only point to a single character, you have to know from context, just as an int * might point to one integer or an array of integers.
Because strings are handy, there's a special syntactical rule for strings literal. A string literal in quotes becomes a const char * (in fact its type is char * for backwards compatibility). So in this sense, C has strings. But all that is happening is that the string is being laid out in the data section of the program, then its address taken.
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 6 years ago.
Improve this question
I have a function which return const char*.
In this function I have the following params:
string str;
For converting str to const char* I use str.c_str().
When I debug I notice that str.c_str() contains something (I guess its address) before the value of the string.
For example:
If str="0"
I str.c_str() wiil 0x68d5f9 "0".
Why is it?
How can I get only the value of the string?
This is not a problem, this is how pointers work.
Pointers point to data contained at some memory address and the debugger shows you that this pointer points to address 0x<something> and the value at this address is '0'. Nothing odd here.
When you print this value you got from str.c_str(), you'll get an ordinary C string.
cout << str.c_str();
This will give you the same as cout << str;
You wouldn't get the address pointed to by the pointer in the string returned by c_str. It is a debugger artifact designed to let programmers inspect the address along with the value.
However, returning the result of c_str may be undefined behavior if the call is made on a function-scoped string.
For example, this is illegal:
const char *illegal_return() {
string s = "quick brown fox";
return s.c_str(); // <<== Return of c_str from a local string
}
The best fix is to return a string. If you would like to return a char pointer instead, you need to make a copy:
char *legal_return() {
string s = "quick brown fox";
const char *ptr = s.c_str();
size_t len = strlen(ptr);
char *res = new char[len+1];
strcpy(res, ptr);
return res;
}
The caller of the above function must call delete[] on the result to avoid memory leaks.
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 8 years ago.
Improve this question
I tried to set simple char with empty value without success. The main goal was to compare between std::string single char and pre-defined char
std::string str ="fcvfr";
char c = '' //trying to set empty char here .... but it gives me error
if(c == str[0])
{
//do something
}
This leads me to the question when should I use each of the following types:
char * , char , char[]
char represents a character (allocated on the stack). If you want to set it to empty, use char c = '\0' or char c = (char) 0.
char* cPtr is a pointer to a character. You can allocate an empty character on the heap with char* c = new char('\0').
char c[n] is a character array of size n.
Edit
As people have correctly pointed out below, a char is never empty, in the same sense as a container such as std::vector or std::string can be empty. A char is not fundamentally different to, say, an int, it's just shorter (1 byte as opposed to 2 or 4 or 8). Can an int be empty? Not as such; it can be zero, meaning that all its bits are set to zero in memory, and the same goes for a char. char c = '\0' will be represented as "00000000" on the stack.
A pointer to a char (char* cPtr), on the other hand can be 'empty' in the sense that it can point nowhere, by setting it to NULL. In this case, the pointer itself will exist on the stack and will contain a special sequence of 0/1's that your system interprets as NULL. Once you do cPtr = new char('\0'), a char (i.e. a byte) will be allocated on the heap and set to "00000000", and the value of cPtr on the stack will be changed to point to the address of the new character on the heap.
PS: don't actually do char* cPtr = new char('\0'), use an std::vector<char> or an std::string. Also, you may want to look into smart pointers.