C/C++: Acces single character from a pointer character single-dimension array - c++

From an initialized Pointer to Array of Characters like this:
char *someChar[]={"Some","Text","Here"};
How would I be able to call for instance, the letter x of "Text", I can't move it's address someChar[1] to some offset to acces x, since this is not a 2-dimensional array.
Using *someChar[1][2] gives the Invalid Indirection Error.
The code is as simple as this: http://ideone.com/OdvocT

That would be someChar[1][2].
someChar[1] is the second array element, which is a pointer to the first letter of "Text".

You can access it as someChar[1][2]. In case of an array of pointers to char, the first dimension of array element is for string and the second is for choosing character in that string.

for every someChar+i{
for every *(someChar+i){
code you logic here
}
}

In C (I have no idea how this all works in C++)
char *someChar[]={"Some","Text","Here"};
is an array of pointers. Each element is a pointer.
someChar[1] is a pointer. It points to a char
*(someChar[1]) is a char, the 'T' (also accessible as someChar[1][0]).
*(someChar[1] + 2) is a char, the 'x' (also accessible as someChar[1][2]).

Related

Why does my pointer to a char only get the first character in it?

I initialized a char and a pointer, and then point it to the char. But I found that only the first character in the char was passed into the pointer. How could this be? Appreciate any advice!
char p[]="This is a long char.";
std::cout<<sizeof(p)<<"\n";
char *ptr=p;
std::cout<<*ptr<<"\n";
Got:
21
T
Program ended with exit code: 0
When checking the value of variables I noticed that:
ptr=(char *) "This is a long char."
*ptr=(char) 'T'
Why is the ptr holding the whole char but the content in it is only the first character? Isn't this the opposite of what we call a pointer? Got really confused...
When you said:
std::cout<<*ptr...
you dereferenced ptr, which gives you the (first) character that ptr is pointing to.
flyingCode's answer shows you how to print the entire string.
In C++, an array is just like multiple variables grouped together, so they each have a memory address, but they are one after another.
So, the pointer is pointing at the address of the first element, and the other elements are in the adresses right after that in order.
When you use the * operator on a pointer, it references the contents of the memory address the pointer is pointing to.
If you wanted to access another element of the array using this, you would use *(ptr + 5) to offset the memory address.
When you use the variable name alone, the language just does the offset for you and gets all the contents of the array. The pointer doesn't know the length of the array, but it can find the end of it, because char arrays always end with a null character (\0).
ran your code in repl and changing it to the code below worked :D
char p[]="This is a long char.";
std::cout<<sizeof(p)<<"\n";
char *ptr=p;
std::cout<<ptr<<"\n"; //notice no *
I recommend you use std::string rather than c-strings unless you have a specific need for them :)

Array of char pointers

I am looking at some code I did not write and wanted help to understand an element of it. The code stores character arrays, creates pointers to these arrays (assigning the pointers the arrays addresses). It looks like it then creates an array to store these characters pointers addresses and I just wanted some clarification on what I am looking at exactly. I also am confused about the use of the double (**) when creating the array.
I have included a stripped down and simplified example of what I am looking at below.
char eLangAr[20] = "English";
char fLangAr[20] = "French";
char gLangAr[20] = "German";
char* eLangPtr = eLangAr;
char* fLangPtr = fLangAr;
char* gLangPtr = gLangAr;
char **langStrings [3]=
{
&eLangPtr,
&fLangPtr,
&gLangPtr
};
When using the array they pass it as an argument to a function.
menu (*langStrings[0]);
So the idea is that the character array value "English" is passed to the function but I'm having trouble seeing how. They pass the menu function a copy of the value stored in the langStrings function at location 0, which would be the address of eLandPtr? If someone could explain the process in English so I could get my head around it that would be great. It might be just because it has been a long day but its just not straight in my head at all.
You are correct that langStrings contains pointers to pointers of array of characters. So each langString[i] points to a pointer. That pointer points to an array. That array contains the name of a language.
As others point out, it looks a bit clumsy. I'll elaborate:
char eLangAr[20] = "English"; is an array of 20 chars and the name "English" is copied to it. I don't expect that variable eLangAr will ever contain something else than this language name, so there is no need to use an array; a constant would be sufficient.
char **langStrings [3]= ... Here, it would be sufficient to have just one indirection (one *) as there seems no need to ever have the pointer point to anything else (randomly shuffle languages?).
in conclusion, just having the following should be sufficient:
const char *langStrings [3]=
{
"English",
"French",
"German"
};
(Note the const as the strings are now read-only constants/literals.)
What the given code could be useful for is when these language names must be spelled differently in different languages. So
"English",
"French",
"German" become "Engels", "Frans", "Duits". However, then there still is one level of indirection too many and the following would be sufficient:
char *langStrings [3]=
{
aLangArr,
fLangAr,
gLangAr
};
Ok, here goes.
The **ptrToptr notation means a pointer to a pointer. The easiest way to think on that is as a 2D matrix - dereferencing one pointer resolves the whole matrix to just one line in the matrix. Dereferencing the second pointer after that will give one value in the matrix.
This declaration:
char eLangAr[20] = "English";
Declares an array of length 20, type char and it contains the characters 'E', 'n', 'g', 'l', 'i', 's', 'h' '\0'
so it is (probably) null terminated but not full (there are some empty characters at the end). You can set a pointer to the start of it using:
char* englishPtr = &eLangAr[0]
And if you dereference englishPtr, it'll give the value 'E'.
This pointer:
char* eLangPtr = eLangAr;
points to the array itself (not necessarily the first value).
If you look at
*langStrings[0]
You'll see it means the contents (the dereferencing *) of the pointer in langStrings[0]. langStrings[0] is the address of eLangPtr, so dereferencing it gives eLangPtr. And eLangPtr is the pointer to the array eLangAr (which contains "English").
I guess the function wants to be able to write to eLangAr, so make it point to a different word without overwriting "English" itself. It could just over-write the characters itself in memory, but I guess it wants to keep those words safe.
** represents pointer to pointer. It's used when you have to store pointer for another pointer.
Value of eLangPtr will be pointer to eLangAr which will has the value "English"
Here:
char eLangAr[20] = "English";
an array is created. It has capacity of 20 chars and contains 8 characters - word "English" and terminating NULL character. Since it's an array, it can be used in a context where pointer is expected - thanks to array-to-pointer decay, which will construct a pointer to the first element of an array. This is done here:
char* eLangPtr = eLangAr;
Which is the same as:
char* eLangPtr = &eLangAr[0]; // explicitly get the address of the first element
Now, while char* represents pointer to a character (which means it points to a single char), the char** represents a pointer to the char* pointer.
The difference:
char text[] = "Text";
char* chPointer = &ch[0];
char** chPointerPointer = &chPointer; // get the address of the pointer
std::cout << chPointer; // prints the address of 'text' array
std::cout << *chPointer; // prints the first character in 'text' array ('T')
std::cout << chPointerPointer; // prints the address of 'chPointer'
std::cout << *chPointerPointer; // prints the value of 'chPointer' which is the address of 'text' array
std::cout << *(*chPointerPointer); // prints the first character in 'text' array ('T')
As you can see, it is simply an additional level of indirection.
Pointers to pointers are used for the same reason "first-level" pointers are used - they allow you to take the address of a pointer and pass it to a function which may write something to it, modifying the content of the original pointer.
In this case it is not needed, this would be sufficient:
const char *langStrings [3]=
{
eLangPtr,
fLangPtr,
gLangPtr
};
And then:
menu (langStrings[0]);

Char 2D Array treats characters separately

Am I able to get the whole number out of char table? For example:
char *table[]={"A","123","2"};
I want to display number 123, but whenever i call
cout<<*table[1];
I get
1
Am I able to fix this ?
When writing char *table[]={"A","123","2"}, your declaring an array of char pointers. In a sense this is a 2 dimensional array and you would print "123" using:
for( unsigned i=0; table[j][i]!='\0'; ++i ) //given j = 1
{
cout << table[j][i];
}
Output:
123
If you look at an operator precedence table for C++, you will find that array subscripting [] is higher precedence than pointer dereferencing *. This, then, is what is happening.
table is an array of pointers. The pointers in the array point to the first character of a string. The next character in the string is simply the next char in memory. The end of the string is the first character whose value is (as an integer) 0, called the null terminator.
When you access table[1], you get the element in the array at index 1, a pointer to a char, which represents a string. When you access *table[1], you get the element in the array at index 1, a pointer to a char, and then dereference that pointer, to get the char it points to.

How does printf display a string from a char*?

Consider a simple example
Eg: const char* letter = "hi how r u";
letter is a const character pointer, which points to the string "hi how r u". Now when i want to print the data or to access the data I should use *letter correct?
But in this situation, shouldn't I only have to use the address in the call to printf?
printf("%s",letter);
So why is this?
*letter is actually a character; it's the first character that letter points to. If you're operating on a whole string of characters, then by convention, functions will look at that character, and the next one, etc, until they see a zero ('\0') byte.
In general, if you have a pointer to a bunch of elements (i.e., an array), then the pointer points to the first element, and somehow any code operating on that bunch of elements needs to know how many there are. For char*, there's the zero convention; for other kinds of arrays, you often have to pass the length as another parameter.
Simply because printf has a signature like this: int printf(const char* format, ...); which means it is expecting pointer(s) to a char table, which it will internally dereference.
letter does not point to the string as a whole, but to the first character of the string, hence a char pointer.
When you dereference the pointer (with *) then you are referring to the first character of the string.
however a single character is much use to prinf (when print a string) so it instead takes the pointer to the first element and increments it's value printing out the dereference values until the null character is found '\0'.
As this is a C++ question it is also important to note that you should really store strings as the safe encapulated type std::string and you the type safe iostreams where possible:
std::string line="hi how r u";
std::cout << line << std::endl;
%s prints up to the first \0 see: http://msdn.microsoft.com/en-us/library/hf4y5e3w.aspx, %s is a character string format field, there is nothing strange going on here.
printf("%s") expect the address in order to go through the memory searching for NULL (\0) = end of string. In this case you say only letter. To printf("%c") would expect the value not the address: printf("%c", *letter);
printf takes pointers to data arrays as arguments. So, if you're displaying a string (a type of array) with %s or a number with %d, %e, %f, etc, always pass the variable name without the *. The variable name is the pointer to the first element of the array, and printf will print each element of the array by using simple pointer arithmetic according to the type (char is 1 or 2 bytes, ints are 4, etc) until it reaches an EOL or zero value.
Of course, if you make a pointer to the array variable, then you'd want to dereference that pointer with *. But that's more the exception than the rule. :)

strcat query (string.h)

First off :
STRCAT :
Cplusplus - strcat
When clearly the definition says :
char * strcat ( char * destination, const char * source );
Why'd they use char str[80] in the example???
Shouldn't they have used a character pointer?
That is because arrays decay into pointers in C/C++. If you define char s[80] the value of s will be the address of the first character i.e &s[0]
array can also be used as pointer. what strcat needs is the pointer to a memory in which it copies the destination string. In this case str[80] will give you the memory that can hold 80 chars.
char str[80];
declares an array of 80 characters.
However, in C and C++, arrays are implicitly converted to pointers. When you pass an array to a function (such as strcat), it automatically "decays", forming a pointer to the first element of the array.
That's not the same as saying that arrays and pointers are the same thing. They aren't. For example, sizeof() yields different results on the above array, and a char*.
An array is, strictly speaking, a pointer to the beginning of a block of memory. So str is a char * that points to the beginning of 80 characters.
When you index into an array, say position 53, the following is equivalent: str[53] is the same as *(str + 53) as str is just a char * and adding 53 to a character pointer will return a pointer so to get the value inside you have to use an asterisk to dereference the pointer. In effect array notation just makes code more readable in certain circumstances.
Actually a great little trick with arrays of char is when you want to skip over some leading text when copying a string. E.g. let's say your array str[80] contains the string "1023: error in code!". And you want to display just the string without the number in front. In this case you could say printf( "%s", str + 6 ) and only "error in code!" would be printed.
char str[80];
Edit:
Opps, I rushed my answer. As dribeas says the statement declares an array and str can be implicitly converted into a pointer when it is used. For instance:
++str;
is an invalid operation while:
char* ptr;
++ptr;
isn't.