Convert char[][] to char** - c++

I have a char[][]
char c[2][2]={
{'a','b'},
{'c','d'}
};
How can I convert it to char**?
The objective here is to use the converted char** as an input for a main function, which only accepts char** as its input. Both C/C++ solutions are acceptable.

While you could easily switch from char[] to char*, the same is not possible with char[][] and char**:
your char[2][2] is a 2 dimensional array having all the elements stored contiguously. To access one element, the compiler computes the offset knowing the size of each row.
char** points to an array that contains pointers to char. To access one element, your compiler computes the offset of the pointer in the left-most, load that poitner, then access to the element.
Workaround:
char *pc[2]={c[0],c[1]};
cout << pc[1][1]<<endl; // prints out the same as c[1][1]
// you can pass `pc` when a `char**` is needed
Remark: this compiles perfectly. However, some functions with an argument like char **av expect in reality av[i] to be a null terminated c-string. In this case, although your code would compile, the results might not be what you expect (buffer overflow).

You cannot convert a char[2][2] to char**, you can only convert it to char(*)[2],
char (*p)[2] = c;
The above is a pointer to array-of-2-char. Note that you need this 2 and cannot just write char** p, since in the latter case you are not able to perform pointer arithmetic (the pointer won't know how many elements to "jump" when incrementing, and you won't be able to address the elements of your array (in this case the rows)).

You could pass the array into the function like this:
char c[2][2] = {
{'a','b'},
{'c','d'}
};
char* x[] { c[0], c[1] };
func(x); // Assuming something like: void func(char** p);

NOTE: Although this answer may explain/illustrate the problem quite well other answers are preferable that recommend creating an automatic variable char*[2]; rather than allocating with new as this answer does.
Original answer:
The problem is char c[2][2] is a contiguous block of char. The compiler allocates only 4 char objects.
When you build an array of arrays (char** c) you need to manually allocate an array of pointers to char and then allocate (or assign) and array of char to each of those pointers.
So to convert your array char c[2][2] to an array of arrays you have to first create the array of pointers and then assign the array of the first element of each array of char to that.
Something like this:
void func(char** c)
{
for(int x = 0; x < 2; ++x)
for(int y = 0; y < 2; ++y)
std::cout << c[x][y] << ' ';
std::cout << '\n';
}
int main(int, char* argv[])
{
// one contiguous block of 4 chars
char c[2][2]={
{'a','b'},
{'c','d'}
};
char** param = new char*[2]; // create your own pointer array
param[0] = &c[0][0]; // assign the first element of each char array
param[1] = &c[1][0];
func(param); // call your func
delete[] param; // cleanup
}
If you have C++11 you can use a smart pointer to prevent memory leaks if an exception is thrown or someone forgets to delete.
int main(int, char* argv[])
{
// one contiguous block of 4 chars
char c[2][2]={
{'a','b'},
{'c','d'}
};
// use a smart pointer
std::unique_ptr<char*[]> param(new char*[2]);
param[0] = &c[0][0];
param[1] = &c[1][0];
func(param.get()); // now if this throws, no memory leak
// delete[] param; // NO NEED TO DELETE
}

Related

get the size of a pointer to an array [duplicate]

I am writing a simple function that returns the largest integer in an array. The problem I am having is finding the number of elements in the array.
Here is the function header:
int largest(int *list, int highest_index)
How can I get the number of integers in the array 'list'.
I have tried the following methods:
int i = sizeof list/sizeof(int); //returns incorrect value
int i = list.size(); // does not compile
Any help will be greatly appreciated!
C++ is based on C and inherits many features from it. In relation to this question, it inherits something called "array/pointer equivalence" which is a rule that allows an array to decay to a pointer, especially when being passed as a function argument. It doesn't mean that an array is a pointer, it just means that it can decay to one.
void func(int* ptr);
int array[5];
int* ptr = array; // valid, equivalent to 'ptr = &array[0]'
func(array); // equivalent to func(&array[0]);
This last part is the most relevant to your question. You are not passing the array, you are passing the address of the 0th element.
In order for your function to know how big the incoming array is, you will need to send that information as an argument.
static const size_t ArraySize = 5;
int array[ArraySize];
func(array, ArraySize);
Because the pointer contains no size information, you can't use sizeof.
void func(int* array) {
std::cout << sizeof(array) << "\n";
}
This will output the size of "int*" - which is 4 or 8 bytes depending on 32 vs 64 bits.
Instead you need to accept the size parameters
void func(int* array, size_t arraySize);
static const size_t ArraySize = 5;
int array[ArraySize];
func(array, ArraySize);
Even if you try to pass a fixed-sized array, it turns out this is syntactic sugar:
void func(int array[5]);
http://ideone.com/gaSl6J
Remember how I said that an array is NOT a pointer, just equivalent?
int array[5];
int* ptr = array;
std::cout << "array size " << sizeof(array) << std::endl;
std::cout << "ptr size " << sizeof(ptr) << str::endl;
array size will be 5 * sizeof(int) = 20
ptr size will be sizeof(int *) which will be either 4 or 8 bytes.
sizeof returns the size of the type being supplied, if you supply an object then it deduces the type and returns the size of that
If you want to know how many elements of an array are in the array, when you have the array and not a pointer, you can write
sizeof(array) / sizeof(array[0])
or
sizeof(array) / sizeof(*array)
There's no way to do that. This is one good reason (among many) to use vectors instead of arrays. But if you must use an array then you must pass the size of the array as a parameter to your function
int largest(int *list, int list_size, int highest_index)
Arrays in C++ are quite poor, the sooner you learn to use vectors the easier you will find things.
Pointers do not have information about the number of elements they refer to. If you are speaking about the first argument of the function call then if list is an array you can indeed use the syntax
sizeof( list ) / sizeof( int )
I would like to append that there are three approaches. The first one is to use arrays passed by reference. The second one is to use pointer to the first element and the number of elements. And the third one is to use two pointers - the start pointer and the last pointer as standard algorithms usually are defined. Character arrays have an additional possibility to process them.
The simple answer is you cannot. You need to store it in a variable. The great advantage with C++ is it has STL and you can use vector. size() method gives the size of the vector at that instant.
#include<iostream>
#include<vector>
using namespace std;
int main () {
vector<int> v;
for(int i = 0; i < 10; i++) {
v.push_back(i);
}
cout << v.size() << endl;
for(int i = 0; i < 10; i++) {
v.push_back(i);
}
cout << v.size() << endl;
return 0;
}
output:
10
20
Not tested. But, should work. ;)
You need to remember in a variable array size, there is no possibility to retrieve array size from pointer.
const int SIZE = 10;
int list[SIZE];
// or
int* list = new int[SIZE]; // do not forget to delete[]
My answer uses a char array instead of an integer array but I do hope it helps.
You can use a counter until you reach the end of the array. Char arrays always end with a '\0' and you can use that to check the end of the array is reached.
char array[] = "hello world";
char *arrPtr = array;
char endOfString = '\0';
int stringLength = 0;
while (arrPtr[stringLength] != endOfString) {
stringLength++;
}
stringLength++;
cout << stringLength << endl;
Now you have the length of the char array.
I tried the counting the number of integers in array using this method. Apparently, '\0' doesn't apply here obviously but the -1 index of the array is 0. So assuming that there is no 0, in the array that you are using. You can replace the '\0' with 0 in the code and change the code to use int pointers and arrays.

Using sizeof() to determine ArraySize [duplicate]

I am writing a simple function that returns the largest integer in an array. The problem I am having is finding the number of elements in the array.
Here is the function header:
int largest(int *list, int highest_index)
How can I get the number of integers in the array 'list'.
I have tried the following methods:
int i = sizeof list/sizeof(int); //returns incorrect value
int i = list.size(); // does not compile
Any help will be greatly appreciated!
C++ is based on C and inherits many features from it. In relation to this question, it inherits something called "array/pointer equivalence" which is a rule that allows an array to decay to a pointer, especially when being passed as a function argument. It doesn't mean that an array is a pointer, it just means that it can decay to one.
void func(int* ptr);
int array[5];
int* ptr = array; // valid, equivalent to 'ptr = &array[0]'
func(array); // equivalent to func(&array[0]);
This last part is the most relevant to your question. You are not passing the array, you are passing the address of the 0th element.
In order for your function to know how big the incoming array is, you will need to send that information as an argument.
static const size_t ArraySize = 5;
int array[ArraySize];
func(array, ArraySize);
Because the pointer contains no size information, you can't use sizeof.
void func(int* array) {
std::cout << sizeof(array) << "\n";
}
This will output the size of "int*" - which is 4 or 8 bytes depending on 32 vs 64 bits.
Instead you need to accept the size parameters
void func(int* array, size_t arraySize);
static const size_t ArraySize = 5;
int array[ArraySize];
func(array, ArraySize);
Even if you try to pass a fixed-sized array, it turns out this is syntactic sugar:
void func(int array[5]);
http://ideone.com/gaSl6J
Remember how I said that an array is NOT a pointer, just equivalent?
int array[5];
int* ptr = array;
std::cout << "array size " << sizeof(array) << std::endl;
std::cout << "ptr size " << sizeof(ptr) << str::endl;
array size will be 5 * sizeof(int) = 20
ptr size will be sizeof(int *) which will be either 4 or 8 bytes.
sizeof returns the size of the type being supplied, if you supply an object then it deduces the type and returns the size of that
If you want to know how many elements of an array are in the array, when you have the array and not a pointer, you can write
sizeof(array) / sizeof(array[0])
or
sizeof(array) / sizeof(*array)
There's no way to do that. This is one good reason (among many) to use vectors instead of arrays. But if you must use an array then you must pass the size of the array as a parameter to your function
int largest(int *list, int list_size, int highest_index)
Arrays in C++ are quite poor, the sooner you learn to use vectors the easier you will find things.
Pointers do not have information about the number of elements they refer to. If you are speaking about the first argument of the function call then if list is an array you can indeed use the syntax
sizeof( list ) / sizeof( int )
I would like to append that there are three approaches. The first one is to use arrays passed by reference. The second one is to use pointer to the first element and the number of elements. And the third one is to use two pointers - the start pointer and the last pointer as standard algorithms usually are defined. Character arrays have an additional possibility to process them.
The simple answer is you cannot. You need to store it in a variable. The great advantage with C++ is it has STL and you can use vector. size() method gives the size of the vector at that instant.
#include<iostream>
#include<vector>
using namespace std;
int main () {
vector<int> v;
for(int i = 0; i < 10; i++) {
v.push_back(i);
}
cout << v.size() << endl;
for(int i = 0; i < 10; i++) {
v.push_back(i);
}
cout << v.size() << endl;
return 0;
}
output:
10
20
Not tested. But, should work. ;)
You need to remember in a variable array size, there is no possibility to retrieve array size from pointer.
const int SIZE = 10;
int list[SIZE];
// or
int* list = new int[SIZE]; // do not forget to delete[]
My answer uses a char array instead of an integer array but I do hope it helps.
You can use a counter until you reach the end of the array. Char arrays always end with a '\0' and you can use that to check the end of the array is reached.
char array[] = "hello world";
char *arrPtr = array;
char endOfString = '\0';
int stringLength = 0;
while (arrPtr[stringLength] != endOfString) {
stringLength++;
}
stringLength++;
cout << stringLength << endl;
Now you have the length of the char array.
I tried the counting the number of integers in array using this method. Apparently, '\0' doesn't apply here obviously but the -1 index of the array is 0. So assuming that there is no 0, in the array that you are using. You can replace the '\0' with 0 in the code and change the code to use int pointers and arrays.

How to get size of an array through pointer? [duplicate]

I am writing a simple function that returns the largest integer in an array. The problem I am having is finding the number of elements in the array.
Here is the function header:
int largest(int *list, int highest_index)
How can I get the number of integers in the array 'list'.
I have tried the following methods:
int i = sizeof list/sizeof(int); //returns incorrect value
int i = list.size(); // does not compile
Any help will be greatly appreciated!
C++ is based on C and inherits many features from it. In relation to this question, it inherits something called "array/pointer equivalence" which is a rule that allows an array to decay to a pointer, especially when being passed as a function argument. It doesn't mean that an array is a pointer, it just means that it can decay to one.
void func(int* ptr);
int array[5];
int* ptr = array; // valid, equivalent to 'ptr = &array[0]'
func(array); // equivalent to func(&array[0]);
This last part is the most relevant to your question. You are not passing the array, you are passing the address of the 0th element.
In order for your function to know how big the incoming array is, you will need to send that information as an argument.
static const size_t ArraySize = 5;
int array[ArraySize];
func(array, ArraySize);
Because the pointer contains no size information, you can't use sizeof.
void func(int* array) {
std::cout << sizeof(array) << "\n";
}
This will output the size of "int*" - which is 4 or 8 bytes depending on 32 vs 64 bits.
Instead you need to accept the size parameters
void func(int* array, size_t arraySize);
static const size_t ArraySize = 5;
int array[ArraySize];
func(array, ArraySize);
Even if you try to pass a fixed-sized array, it turns out this is syntactic sugar:
void func(int array[5]);
http://ideone.com/gaSl6J
Remember how I said that an array is NOT a pointer, just equivalent?
int array[5];
int* ptr = array;
std::cout << "array size " << sizeof(array) << std::endl;
std::cout << "ptr size " << sizeof(ptr) << str::endl;
array size will be 5 * sizeof(int) = 20
ptr size will be sizeof(int *) which will be either 4 or 8 bytes.
sizeof returns the size of the type being supplied, if you supply an object then it deduces the type and returns the size of that
If you want to know how many elements of an array are in the array, when you have the array and not a pointer, you can write
sizeof(array) / sizeof(array[0])
or
sizeof(array) / sizeof(*array)
There's no way to do that. This is one good reason (among many) to use vectors instead of arrays. But if you must use an array then you must pass the size of the array as a parameter to your function
int largest(int *list, int list_size, int highest_index)
Arrays in C++ are quite poor, the sooner you learn to use vectors the easier you will find things.
Pointers do not have information about the number of elements they refer to. If you are speaking about the first argument of the function call then if list is an array you can indeed use the syntax
sizeof( list ) / sizeof( int )
I would like to append that there are three approaches. The first one is to use arrays passed by reference. The second one is to use pointer to the first element and the number of elements. And the third one is to use two pointers - the start pointer and the last pointer as standard algorithms usually are defined. Character arrays have an additional possibility to process them.
The simple answer is you cannot. You need to store it in a variable. The great advantage with C++ is it has STL and you can use vector. size() method gives the size of the vector at that instant.
#include<iostream>
#include<vector>
using namespace std;
int main () {
vector<int> v;
for(int i = 0; i < 10; i++) {
v.push_back(i);
}
cout << v.size() << endl;
for(int i = 0; i < 10; i++) {
v.push_back(i);
}
cout << v.size() << endl;
return 0;
}
output:
10
20
Not tested. But, should work. ;)
You need to remember in a variable array size, there is no possibility to retrieve array size from pointer.
const int SIZE = 10;
int list[SIZE];
// or
int* list = new int[SIZE]; // do not forget to delete[]
My answer uses a char array instead of an integer array but I do hope it helps.
You can use a counter until you reach the end of the array. Char arrays always end with a '\0' and you can use that to check the end of the array is reached.
char array[] = "hello world";
char *arrPtr = array;
char endOfString = '\0';
int stringLength = 0;
while (arrPtr[stringLength] != endOfString) {
stringLength++;
}
stringLength++;
cout << stringLength << endl;
Now you have the length of the char array.
I tried the counting the number of integers in array using this method. Apparently, '\0' doesn't apply here obviously but the -1 index of the array is 0. So assuming that there is no 0, in the array that you are using. You can replace the '\0' with 0 in the code and change the code to use int pointers and arrays.

getting size of array from pointer c++

I am writing a simple function that returns the largest integer in an array. The problem I am having is finding the number of elements in the array.
Here is the function header:
int largest(int *list, int highest_index)
How can I get the number of integers in the array 'list'.
I have tried the following methods:
int i = sizeof list/sizeof(int); //returns incorrect value
int i = list.size(); // does not compile
Any help will be greatly appreciated!
C++ is based on C and inherits many features from it. In relation to this question, it inherits something called "array/pointer equivalence" which is a rule that allows an array to decay to a pointer, especially when being passed as a function argument. It doesn't mean that an array is a pointer, it just means that it can decay to one.
void func(int* ptr);
int array[5];
int* ptr = array; // valid, equivalent to 'ptr = &array[0]'
func(array); // equivalent to func(&array[0]);
This last part is the most relevant to your question. You are not passing the array, you are passing the address of the 0th element.
In order for your function to know how big the incoming array is, you will need to send that information as an argument.
static const size_t ArraySize = 5;
int array[ArraySize];
func(array, ArraySize);
Because the pointer contains no size information, you can't use sizeof.
void func(int* array) {
std::cout << sizeof(array) << "\n";
}
This will output the size of "int*" - which is 4 or 8 bytes depending on 32 vs 64 bits.
Instead you need to accept the size parameters
void func(int* array, size_t arraySize);
static const size_t ArraySize = 5;
int array[ArraySize];
func(array, ArraySize);
Even if you try to pass a fixed-sized array, it turns out this is syntactic sugar:
void func(int array[5]);
http://ideone.com/gaSl6J
Remember how I said that an array is NOT a pointer, just equivalent?
int array[5];
int* ptr = array;
std::cout << "array size " << sizeof(array) << std::endl;
std::cout << "ptr size " << sizeof(ptr) << str::endl;
array size will be 5 * sizeof(int) = 20
ptr size will be sizeof(int *) which will be either 4 or 8 bytes.
sizeof returns the size of the type being supplied, if you supply an object then it deduces the type and returns the size of that
If you want to know how many elements of an array are in the array, when you have the array and not a pointer, you can write
sizeof(array) / sizeof(array[0])
or
sizeof(array) / sizeof(*array)
There's no way to do that. This is one good reason (among many) to use vectors instead of arrays. But if you must use an array then you must pass the size of the array as a parameter to your function
int largest(int *list, int list_size, int highest_index)
Arrays in C++ are quite poor, the sooner you learn to use vectors the easier you will find things.
Pointers do not have information about the number of elements they refer to. If you are speaking about the first argument of the function call then if list is an array you can indeed use the syntax
sizeof( list ) / sizeof( int )
I would like to append that there are three approaches. The first one is to use arrays passed by reference. The second one is to use pointer to the first element and the number of elements. And the third one is to use two pointers - the start pointer and the last pointer as standard algorithms usually are defined. Character arrays have an additional possibility to process them.
The simple answer is you cannot. You need to store it in a variable. The great advantage with C++ is it has STL and you can use vector. size() method gives the size of the vector at that instant.
#include<iostream>
#include<vector>
using namespace std;
int main () {
vector<int> v;
for(int i = 0; i < 10; i++) {
v.push_back(i);
}
cout << v.size() << endl;
for(int i = 0; i < 10; i++) {
v.push_back(i);
}
cout << v.size() << endl;
return 0;
}
output:
10
20
Not tested. But, should work. ;)
You need to remember in a variable array size, there is no possibility to retrieve array size from pointer.
const int SIZE = 10;
int list[SIZE];
// or
int* list = new int[SIZE]; // do not forget to delete[]
My answer uses a char array instead of an integer array but I do hope it helps.
You can use a counter until you reach the end of the array. Char arrays always end with a '\0' and you can use that to check the end of the array is reached.
char array[] = "hello world";
char *arrPtr = array;
char endOfString = '\0';
int stringLength = 0;
while (arrPtr[stringLength] != endOfString) {
stringLength++;
}
stringLength++;
cout << stringLength << endl;
Now you have the length of the char array.
I tried the counting the number of integers in array using this method. Apparently, '\0' doesn't apply here obviously but the -1 index of the array is 0. So assuming that there is no 0, in the array that you are using. You can replace the '\0' with 0 in the code and change the code to use int pointers and arrays.

c++ pointers:-why is this code not running

int main(int argc, char** argv) {
char a[2][5]={"hell","worl"};
char **p;
p=a; // error here
cout<<*(*(a+1)+1);
cout<<endl;
cout<<(*a)[2];
return 0;
}
error:
C:\Dev-Cpp\main.cpp [Error] initializer-string for array of chars is too long [-fpermissive]
Why would you expect it to work? You declare p as char**,
and you try to assign a char[2][5] to it. The char[2][5]
will convert implicitly to a char (*)[5], but afterwards, you
have a pointer, and no further implicit conversions. (EDIT: except to void*.)
If you think about it, it should be obvious. If you dereference
a char**, you get a char*. And this char* must reside
somewhere in memory, since you have a pointer to it. So where
is it?
If you want to iterate over the outer array in your example:
char (*p)[5] = a;
std::cout << *p[0] << sdt::endl;
std::cout << *p[1] << sdt::endl;
Note that your expression *(*(a+1)+1) also supposes that you
have an array of pointers somewhere.
Or you can use the usual solution when working with C style
strings:
char const* const a[] = { "hell", "worl" };
and
char const* const* p = a;
In this case, you do have an array of pointers, which does
implicitly convert to a pointer to a pointer (the first element
of the array).
(Of course, the only time you'll really want to use C style
strings is with const variables with static lifetimes. In
most other cases, std::string is preferable.)
Other way to access the a[2][5] is,
char **p=(char**)a;
to get a[0]
printf("\n a[0] is [%s]", ((char*)p));
to get a[1]
printf("\n a[1] is [%s]", (((char*)p) + strlen(a[0])+1));
hope this helps.