3

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.

1
  • I sure hope this is just a more or less academic question and that you are using std::vector<std::string> et al in production code... :) Commented Jul 6, 2014 at 11:40

2 Answers 2

8

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] = ...
Sign up to request clarification or add additional context in comments.

2 Comments

#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], "Saurab"); strcpy((*a)[1],"srivastav"); } int main () { char* b = NULL; f(&b); cout<<b[0]<<"\n"; cout<<b[1]<<"\n"; return 1; } Now its working.
Actually *a[0] works because it is correct! *a[0] and (*a)[0] are both a[0][0] - it makes no difference to swap the zeroes around. Cf. *a[1] == a[1][0] but (*a)[1] == a[0][1].
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.