1

This is my test code

#include <QCoreApplication>
#include <QDebug>

void fillData(unsigned char *data){
    data = new unsigned char[10];
    for (int i = 0; i < 10; i++){
        data[i] = static_cast<unsigned char>(i);
    }
    qDebug() << "Returning wiht non null data?" << (data == nullptr);
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    unsigned char *data = nullptr;
    qDebug() << "Is data null" << (data == nullptr);
    fillData(data);
    qDebug() << "Is data null" << (data == nullptr);

    return a.exec();
}

I need to fill a pointer to array of bytes inside a fucntion and I was noting in my application that I kept getting null. So I wrote this MWE. It reproduces the problem as the output for this program is

Is data null true
Returning wiht non null data? false
Is data null true

When I would expect the theird question to return false. I can't figure out what I'm doing wrong.

ikegami
  • 367,544
  • 15
  • 269
  • 518
aarelovich
  • 5,140
  • 11
  • 55
  • 106
  • 1
    `data` is passed as a copy. – tkausl Dec 15 '19 at 12:11
  • So how do I make sure that I pass it as reference when it's already a pointer? Sorry about the noob question but I actively avoid using these data types and now I'm required to use it for a part in my current app – aarelovich Dec 15 '19 at 12:12
  • @aarelovich in C pass a pointer to a pointer, in C++ pass a reference to the pointer. Obviously you cal also return the pointer. – AProgrammer Dec 15 '19 at 12:13

1 Answers1

4

The function deals with a copy of the original variable. Function parameters are its local variables.

You have to pass the pointer by reference in the C++ meaning or in the C meaning. For example

C++ passing by reference

void fillData(unsigned char * &data){
    data = new unsigned char[10];
    for (int i = 0; i < 10; i++){
        data[i] = static_cast<unsigned char>(i);
    }
    qDebug() << "Returning wiht non null data?" << (data == nullptr);
}

C passing by reference

void fillData(unsigned char **data){
    *data = new unsigned char[10];
    for (int i = 0; i < 10; i++){
        ( *data )[i] = static_cast<unsigned char>(i);
    }
    qDebug() << "Returning wiht non null data?" << (*data == nullptr);
}

In this case the function call will look like

fillData( &data );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335