Create array of pointers in C++ [closed] - c++

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.

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'.

How is a const char* not a just a character? [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 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.

Difference between char , char[] , char * [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 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.

Can you use sizeof() to print the size of an array pointed to by char *? [duplicate]

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 9 years ago.
char *one = new char[1024];
char one1[] = "hello";
one = hello;
cout << sizeof(one) << endl;
I really want the last line to output sizeof(one1) but I know as it stands it will output the size of the pointer which is 4 or 8. Is there a way to extract the sizeof() of the array from just the pointer to the first letter?
Is there a way to extract the sizeof() of the array from just the pointer to the first letter?
No.
Unfortunately, you have to keep track of this explicitly and maybe pass around the length as extra arguments to functions etc.
You have tagged your question "C++". In C++ we usually use std::vector, std::string or other container classes to keep track of this.
There is no way to do this - maybe use a std::vector instead, or a std::string if you just need char's.
No.
That information is simply not available at run-time. A pointer is just a pointer, there is nowhere for the extra information (about the area being pointed at) to live.

difference between char array and string in cplusplus [duplicate]

This question already has answers here:
What is the difference between a Character Array and a String?
(10 answers)
Closed 9 years ago.
I want to know the difference between character array and string in c++.
Can any one answer to this??
Please,
Thanks
Vishnukumar
string is a class/object, with methods and encapsulated data.
A char array is simply a contiguous block of memory meant to hold chars.
(1) char array is just a block of char type data:
e.g. char c[100]; // 100 continuous bytes are allotted to c
(2a) By string, if you mean char string then, it's little similar to array but it's allocated in the readonly segment of the memory and should be assigned to a const char*:
e.g. const char *p = "hello"; // "hello" resides in continuous character buffer
[note: char c[] = "hello"; belongs to category (1) and not to (2a)]
(2b) By string if yo umean std::string then, it's a standard library class from header and you may want to refer its documentation or search on web