Char 2D Array treats characters separately - c++

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.

Related

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]);

Understanding char array[] and string

I am new to programming. I am learning C as my first programming language. I found something strange to understand.
I have learnt that in C we can represent a String as a sequence of characters like this (using a char array):
char status[10] = "Married";
I have learnt that the problem of this approach is that we have to tell the size of the status array during compilation.
But now I have learned we can use a char pointer to denote an string like -
char status[10] = "Married";
char *strPtr;
strPtr = status;
I don't understand it properly. My questions are -
How can I get char at index 4 (that is i in Married) using the strPtr?
In status there is a null character (\0) at the end of the string represented by the char array - M-a-r-r-i-e-d-\0. So by using the null character (\0) we can understand the end of the string. When we use strPtr, how can we understand the end of the string?
char *strPtr;
strPtr = status;
Now your pointer strPtr is pointing to the first character in the array and you can do
int i =0;
while( strPtr[i] != '\0')
{
printf("%c ",strPtr[i]);
i++;
}
*strPtr is called dereferencing the pointer to get the value stored in the location the pointer is pointing to.
Make a note that
strPtr[4] = *(strPtr +4);
Both will get you the value stored at the index 4 of the array.
Note the difference between a pointer and a array name:
----------------------------------
| s | t | r | i | n | g | \0 |
----------------------------------
|
strPtr
status
strPtr ++ will make your pointer point to the next element in the array.
| s | t | r | i | n | g | \0 |
----------------------------------
|
strPtr
Whereas you can't do this for the array name
status++ is not allowed because an array is not a modifiable lvalue.
Good to know:
char status[10] = "Married";
is just syntax sugar for the equivalent:
char status[10]; // allocate 10 Bytes on stack
status[0] = 'M';
status[1] = 'a';
...
status[6]= 'd';
status[7] = '\0'; // same as 0
Nothing more, nothing less.
Also:
char c = status[3];
is exactly the same as
char c = *(status+3);
The expression status[10] is mere syntactic sugar for *(status+10).
The \0 termination is used under the hood to check for the end, if you were implementing some string-handler yourself you could do this too, or you could ignore it and use some other parameter size given with the string, or you could (don't!) choose anything else as the termination symbol.
This isn't just true of char arrays, or 'strings', a C array is just a pointer to a contiguous block of like-typed stuff with a compile-time check that your 'array' subscripts don't go beyond the 'end' specified at time of declaration. With the *(array+offset) notation, you need to check this for yourself.
To get character at index 4 strPtr, you just use strPtr[4] (this also work for status).
To get the end of the string when using strPtr, you need to go through the characters and look for the terminating \0. This is what printf("%s", strPtr) does when it prints the string (and also when it parses the "%s" expression, which is just another string). To find a number of valid characters in the string in C, you use strlen() function. Oh, and make sure you dont do something like this:
char a[3];
strcpy(a, "Hello!");
As this will write 7 bytes into a three-byte memory space, and hence overwrite something you don't want overwritten.
I'm going to make a provocative statement: the way to think of this is that C doesn't have strings. C only has arrays of char. And despite its name, char is actually a numeric type ('A', for example, is just a funny way to write a number, usually 65).
An array of char is not really different from an array of int or any other array of numeric type; it's just that the language offers some extra ways to write objects of type char and arrays of them, and there is a general convention (systematized with functions like strlen) for how to interpret data stored in char arrays as being representations of strings.
char status[10]; // declares an array of `char` of length 10.
char *strPtr; // declare a pointer to `char`
strPtr = status; // make `strPtr` point to the first element of `status`
// Declare an array of 6 `char`, and initialize it.
char hello[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
// Shorthand notation for initializing an array of 6 `char` as above
char world[6] = "World";
// I want to store numeric data in this one!
char other[6] = {0, 1, 2, 3, 4, 5};
// "World" is shorthand for a constant array of 6 `char`. This is
// shorthand for telling the compiler to actually put that array in
// memory someplace, and initialize worldPtr to point to that memory.
const char *worldPtr = "World";
// This does the same thing as above. But it's still a *constant* array.
// You should *never* do this; it should be syntactically illegal to
// make a nonconstant `char*` to point to it. This is only allowed for
// historical reasons.
char *helloPtr = "Hello";
The '\0' at the end of the string is a useless add-on designed for easy or safety. You can tell string last character by using 'sizeof' like this:
char status[] = "Married";
size_t szLastCharstatus = sizeof(status) / sizeof(status[0]) - 2;
char chLastChar = status[szLastCharstatus];
Detailed explanation:
sizeof(status)
Returns the number of bytes array occpuies.
sizeof(status[0])
Returns the number of bytes first element occupies (and so the rest).
The division between those 2 values gives us the number of elements in the array. To access the last element now we need to subtract one 2 times because elements in array count from zero and because the last character in the string is '\0'.
Also note that arrays are not pointers and vice-versa. Arrays have an implicit conversion to pointer of their first element, constant size and their own type. They can be passed around by pointers or by value (using structure hack is required for the second).
Note that I'm using 'size_t' which is a type-def of a variable storing some size of data.

c++ pointers and string of characters

am a bit confused about something in string of characters and pointers regarding c++ language ..
well, i came to know that a name of an array of characters is actually the address of it's first element and i also know that The cout object assumes that the address of a char is the address of a string, so it prints the character at that address and then continues printing characters until it runs into the null character (\0).
but here is the interesting part i tried this code in codeblocks
char arr[10]="bear";
cout <<&arr<<endl; // trying to find the address of the whole string
cout<<(int *)arr<<endl; // another way of finding the address of the string
cout<<(int *)arr[0]<<endl; // trying to find the address of the first element
what came on the screen was as follows
0x22fef6,
0x22fef6,
(0x62) <<<< My question is , what the heck is that? .. If the arrayname holds the address of the first element , shouldn't the first element address be " 0x22fef6 " ???????????????????
The [] operator does not return an address but dereferences the pointer at the given offset.
You could write an equivalent to the [] operator as follows:
char arr[10] = "bear";
char c = *(arr+0); // == arr[0] == 'b'
That is, you take the pointer arr, increase it by 0 char and then dereferences it to get it's value.
char arr[10]="bear";
cout <<&arr<<endl;
cout<<(int *)arr<<endl;
cout<<(int *)(arr+0)<<endl; // increases the address by 0
cout<<(int *)(&arr[0])<<endl; // the address of the value at index 0
This would do what you have expected it to do.
arr[0] equals *(arr + 0); you dereference the pointer and obtain the value it holds. To get what you want you need to reference the element, like &arr[0].

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

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]).

What is the difference between int and char arrays?

What is the difference between int and char arrays below:
int main()
{
int numbers[] = {2,1,3};
char letter[] = {'a','b','\0'};
cout<< numbers<<endl;
cout<< letter<<endl;
}
Output:
0x22ff12 // an address
ab
Why isn't the 213 displayed ?
I know the name of an array will point to the address of its first element, but why
does a char array display different behavior?
There is no operator<< overload that takes arrays, exactly, so the arguments you pass (eg numbers and letter) undergo array-to-pointer conversion, to void* and char* respectively.
There is an overload of operator<<() that takes a const void*, and another that takes a const char*. When you call:
cout<< numbers<<endl;
the const void* version is matched, but when you call:
cout<< letter<<endl;
the const char* version is matched.
In the const void* version, the pointer is displayed, while with the const char* version, the string is displayed up to the null terminator.
When you print an array with cout it will print the base address of the array.
The exception is with char arrays which have been overloaded to print it as a c-string.
If you want to print the elements of the int array, you need to do it element-by-element.
The reason is thatoperator<< overloaded for const char* which prints each character till it encounters \0.
There is no such overload corresponds to int[N] which prints each element in it. Instead when you write cout << numbers, it invokes operator<< which is overloaded for void*, and which prints the address.
However, if you overload operator<< for T[N], then you can print it like that as well.
Here is a simple illustration:
template<typename T, size_t N>
std::ostream & operator<<(std::ostream & out, const T (&a)[N])
{
for(size_t i = 0 ; i < N ; ++i)
out << a[i] << ' ';
return out;
}
int main()
{
int numbers[] = {2,1,3};
char letter[] = {'a','b','\0'};
cout<< numbers<<endl;
cout<< letter<<endl;
}
Output:
2 1 3
a b
Demo : http://ideone.com/O4T9N
In C, and therefore in C++, a string is often represented by an array of chars terminated in a 0. Therefore an overloaded operator<< is provide for the class std::ostream, of which std::cout is an instance , which prints the char* as a string. There is no such common use of int arrays, nor any convention so the operator would 'know' how many elements to output, so the pointer to the array is matched to the version of operator<< which outputs any other pointer by printing its address.
char arrays are special because there is an overload for operator << that displays the content as a string.
All other arrays will have the address displayed by default.
In C/C++ an array is in fact a pointer to the first element. A pointer holds the address where a value is stored. Therefore, if you print the pointer numbers, you will get the address where the first value (2) is stored in memory.
char* is an exception, as it will behave as a string when you try to print it.
Your code mostly refers C. An array of char is de-facto representation of strings in C. On the other hand, an array in C is also a pointer to the memory cell (an address of the cell) that holds the first element of the array.
So, when you print out an array of characters, you in fact print out a string (because C treats it that way). When you're printing an array of integers, you're printing out the address of the first element of the array.
numbers is a pointer. All arrays in C++ are in fact pointers, numbers[3] just means "the value at the memory address &number+3", so you're outputting the memory address of the first element in numbers.
There is no reason the compiler should know where your int[] array ends, but tradition and standard libraries dictate that C strings are null terminated char[] arrays. There is no such tradition or library support for null terminated int[] arrays.
There are C++ pretty printers templates available if you need this functionality. I vaguely recall that one employs an array's bound when the type actually knows the bound, i.e. your code still won't work since you use [] not [3].
Just fyi, your code cannot be fixed by replacing the [] with a [3] inside the STL, although perhaps operator<< could be overloaded.
A char array contains characters.
It can be initialized like:
char arr[4]={'a','b','c','\0'};
char arr[4]={"abc"};
An integer array contains integers.
It can be initialized like:
int arr[4]={1,2,3,4};