Reputation: 663
I have written following sample code to demonstrate my problem
#include <iostream>
#include <string.h>
using namespace std;
void f (char*** a)
{
*a = new (char*[2]);
*a[0] = new char[10];
*a[1] = new char[10];
strcpy(*a[0], "abcd");
strcpy(*a[1],"efgh");
}
int main ()
{
char** b = NULL;
f(&b);
cout<<b[0]<<"\n";
cout<<b[1]<<"\n";
return 1;
}
In this code i found that a = new (char[2]); not allocating memory of *a[1].
In gdb i am getting following seg fault.
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400926 in f (a=0x7fffffffdfe8) at array1.cpp:10
10 *a[1] = new char[10];
(gdb) p *a[1]
Cannot access memory at address 0x0
This is really confusing me. Can someone explain where i am going wrong.
I know i can pass argument like void f (char**& a) and by calling function f(b) and this works . But i want to know want happening if i use char*** a. It should also work. Sorry if this is an stupid question.
Any tutorial or reference on above problem will be appreciated.
Thanks in advance.
Upvotes: 3
Views: 371
Reputation: 166
a[0], a[1] are char, and they have a value in them, dereferencing that value will obviously cause a segmentation fault. What you may want to do is:
(*a)[...]
dereference 'a' which is a pointer, this will give u an array.
Upvotes: 0
Reputation: 409442
It's because of the operator precedence, where the array-indexing operator []
have higher precedence than the dereference operator *
.
So the expression *a[0]
is really, from the compilers point of view, the same as *(a[0])
, which is not what you want.
You have to explicitly add parentheses to change the precedence:
(*a)[0] = ...
Upvotes: 8