I am having problems with array pointers. I've looked through Google and my attempts are futile so far.
What I would like to do is, I have a char name[256]. I will be 10 of those. Hence, I would need to keep track of each of them by pointers.
Trying to create a pointer to them.
int main()
{
char superman[256] = "superman";
char batman[256] = "batman";
char catman[256] = "catman";
char *names[10];
names[0] = superman;
names[1] = batman;
system("pause");
return 0;
}
How do I actually traverse an array of pointers?
A character array is a sequence of characters, just as a numeric array is a sequence of numbers. A typical use is to store a short piece of text as a row of characters in a character vector.
char* is a pointer to a character, which can be the beginning of a C-string. char* and char[] are used for C-string and a string object is used for C++ springs. char[] is an array of characters that can be used to store a C-string.
The fundamental difference is that in one char* you are assigning it to a pointer, which is a variable. In char[] you are assigning it to an array which is not a variable.
Difference between char s[] and char *s in C There are some differences. The s[] is an array, but *s is a pointer. For an example, if two declarations are like char s[20], and char *s respectively, then by using sizeof() we will get 20, and 4. The first one will be 20 as it is showing that there are 20 bytes of data.
names[0] is a char* to whatever you stored in names[0] (which in this case is a pointer to the first element in your superman
array) thus your guess at e.g cout << names[0] << endl;
is correct.
If you want to traverse that array, you need to know when to stop so you're not traversing pointers you havn't yet initialized- if you know you have initialized 2 of those pointers, you could do e.g.
for(int i = 0; i < 2 ; i++) {
std::cout << names[i] << std::endl;
}
As an alternative, place a NULL pointer after the last element you have initialized(make sure there's room for that NULL pointer) e.g.
names[2] = NULL;
for(int i = 0; names[i] != NULL ; i++) {
std::cout << names[i] << std::endl;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With