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.
Related
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'.
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";
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.
This question already has answers here:
How to find the size of an array (from a pointer pointing to the first element array)?
(17 answers)
Closed 7 years ago.
I am having a difficult time obtaining the correct size of a string in order to satisfy strcpy_s. For example if I specify
char buffer = {0};
char *str1 = (char*)&buffer;
strcpy_s(str1,sizeof("This is a string\n"),"This is a string\n");
Then it will work as expected. If however I declare the following:
char buffer = {0};
char *str1 = (char*)&buffer;
const char* string1 = "This is a string.....";
strcpy_s(str1, ?????,string1);
If I use anything other than a literal in place of ????? it will fail with a memory exception, for example if I use std:strlen(str1), etc. Any size literal for ???? will work. Of course using a fixed literal is not acceptable.
This is a major re-edit of the original question and I apologise to the people who have answered to date. However none of the the answers below have worked.
"This is a string" is a character array. When you say sizeof(Array)/sizeof(type) it will give the size of the array
When you define the string as const char* then the sizeof(pointer) gives the size allocated for the pointer no the array size
const char* ptr = "This is a string\n";
std::cout<<sizeof("This is a string\n")<<std::endl; //==>18
std::cout<<sizeof(ptr)<<std::endl; //==>4
First of all, the second parameter is the size of the destination buffer, not the size of the source buffer.
so the correct way is:
char str1[100];
strcpy_s(str1, sizeof str1, "Whatever string");
or
int n = 100;
char *str1 = new char[n];
strcpy_s(str1, n, "whatever string");
For an array (first example) sizeof returns the size of the array.
For a pointer (second example) sizeof returns the size of the pointer (which is not what you want)
In your second example, string1 is of type const char*. sizeof will return the size of the pointer, rather than the length of the string literal you are pointing to.
The first example works because a string literal is a const char[], and sizeof will correctly return the length of the string (but with the null terminating character as well). It's only coincidental that this works because char is 1 byte. Do not use sizeof to get string lengths.
To make your second example work, try using std::strlen.
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 8 years ago.
Improve this question
I see some code written like this:
char str[256] = {0};
or
char str[256] = {1};
when the former case, I use
printf("%s", str);
gives nothing,
Does it means give all the str[0] to str[256] all value 1?
when latterthe stdio give a ASCII smile char.
Furthermore, what is the difference between
char s[256] = {0};
printf("%c", s[1]);
It gives nothing in stdout
char s[256] = {0};
printf("%s", s[1]);
it give a (null)
I do not understand because I am a beginner of c char array and c pointers.
This initializes all 256 chars to 0:
char str[256] = {0};
This one initializes the first one to 1, and all the rest to 0:
char str[256] = {1};
Concerning the behaviour of printf, "%c" expects a single char. You pass it 0, which is NUL (the character string termination) so it prints nothing. "%s" expects a char* with the first character in a nul-terminated character string. You pass it a single char with value 0, which it interprets as a null pointer.