Hi

This whole pointer thing is getting the better of me.

first i have a call to method "convertToCString" in my main:

int value = 21;
char* cstr = NULL

convertToCString(value, &cstr);
printf("\"%s\"\n". &cstr);
cstr = NULL
delete cstr;

the method looks like this

bool convertToCString(int& refConstInt, char** ptrtoCharPtr)
{
      ptrToCharPtr = new char*;
      if (sprintf(*ptrtoCharPtr, "%d", refConstint) > 0)
         return true;
      else 
         return false;
}

I get a segmentation error in the output.

but when i do this:

bool convertToCString(int& refConstInt, char** ptrtoCharPtr)
{
      ptrToCharPtr = new char*;
      char* blah
      if (sprintf(blah, "%d", refConstint) > 0)
         return true;
      else 
         return false;
}

It output the correct value ? How does this work ? I can't make any sense of it.

Recommended Answers

All 5 Replies

Now I could be wrong (because most probably Java has numbed much of my C++ knowledge) but looking at your function :-

bool convertToCString(int& refConstInt, char** ptrtoCharPtr)

It is expecting a reference as its first parameter but you are passing an "int" here.

convertToCString(value, &cstr);

Why would you ever use a pointer to a pointer? Seems like its just asking for problems?

I agree fully to what you have said, the code example is for studying purposes- passing parameters. It's given by our lecturer as an extra exercise.

The exercise is as follow :

The function takes a
reference to a constant integer, and a pointer to a character pointer, as parameters. The function should use sprintf
to convert the integer value to a cstring. The function should allocate memory on the heap for the string to be
stored in, and the character pointer to which the second parameter points should be assigned to this newly
allocated array. The function should return a boolean value indicating whether the conversion was successful.

code from main:

int value = 21;
char* cstr = NULL

convertToCString(value, &cstr);
printf("\"%s\"\n", &cstr);
cstr = NULL
delete cstr;

create a convertToCString function as specified

>Why would you ever use a pointer to a pointer?
Well, you have to if you ever want to take advantage of command line arguments. In C++ a reference to a pointer would be better if you just need a pointer that can be modified in another function, but pointers to pointers are common and useful. The frequency and usefulness becomes progressively less as you add levels of indirection though. The most I've ever seriously used is 5 (a pointer to a pointer to a pointer to a pointer to a pointer).

*ptrToCharPtr = new char[10];

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.