Pointer to pointer in C

Hi Experts,

When using pointer to pointer would the following is valid?
char *value;
int ret = function(&value);

where as function is declared as 
int function(char **val);

Open in new window


Can we get the address of an uninitialized pointer?
ambuliAsked:
Who is Participating?
 
sarabandeConnect With a Mentor Commented:
to add to above answers:

a pointer to pointer as an argument to a function is the c way to return a pointer to the calling function.

int function(char ** ppval)
{
     *ppval = new char[256];
     strcpy(*ppval, "hello world");
     return (int)strlen(*ppval);
}

int main()
{
       char * p = NULL;
       function(&p);
       if (p != NULL)
            std::cout << p << std::endl;

Open in new window


in c++ you would/could use a reference to pointer instead (or use reference to string class object):

int function(char *& pval)
{
     pval = new char[256];
     strcpy(pval, "hello world");
     return (int)strlen(pval);
}

int main()
{
       char * p = NULL;
       function(p);
       if (p != NULL)
            std::cout << p << std::endl;

Open in new window


Sara
0
 
ozoCommented:
yes
0
 
ambuliAuthor Commented:
Thank you.
0
 
evilrixConnect With a Mentor Senior Software Engineer (Avast)Commented:
An uninitialized pointer still has storage, it's just the storage contains an arbitrary value until you initialise it. There is nothing magic about a pointe, it's just a type, just like int is just a type. If you create an int without initializing it storage is still allocated for it; so it is for pointers, too.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.