Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a char pointer array to a function

Tags:

c++

c

pointers

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.

like image 979
SaurabhS Avatar asked Jun 17 '26 22:06

SaurabhS


1 Answers

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] = ...
like image 186
Some programmer dude Avatar answered Jun 20 '26 10:06

Some programmer dude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!