Qt World Summit: Register Today!

Cant access arrey inside the function c++

  • The thing is, i need to create threads and using them sort an arrey.
    Tried in 1 thread. I am using struct to put there limits of an arrey. I can use them. But every time i try to use that arrey - i'm getting an error. Firstly, i tried to put pointer on massive inside the struct. Made it global, but did not help. Can any1 pls help? Here is the code:
    //My struct
    struct t_arg
    int begin;
    int end;
    QTextBrowser *tb;

    //My function
    void * sort(void* arg)
    struct t_arg tmp_arg = *(struct t_arg *) arg;

    int begin = tmp_arg.begin; int end = tmp_arg.end;

    for(int j = begin; j < end; j++)

        for(int i = begin; i < end-1; i++)
            if(mass[i] > mass[i+1]) //Getting error here, if i  comment it - get error below.
                int tmp = mass[i]; mass[i] = mass[i+1];// here(
                mass[i+1] = tmp;
    return NULL;


    //main part
    pthread_t thread; struct t_arg tmp_struct;

    n_qthreads = ui->comboBox->currentText().toInt(); n_e_quantity = ui->spinBox->value();
    mass = new int[n_e_quantity];
    for(int i = 0; i < n_e_quantity; i++)
        mass[i] = rand()0 + 40;

    tmp_struct.begin = 0;

    tmp_struct.end = n_e_quantity;
    tmp_struct.tb = ui->textBrowser;
    pthread_create(&thread, NULL, &sort, &tmp_struct);


    [Added @ around code. andreyc]

  • Welcome to Qt DevNet,

    1. You can not use UI elements in the threads.
    2. You passing an address of local variable tmp_struct to pthread_create(). At the time when the thread is started this variable is gone and you are accessing invalid pointer. Allocate tmp_struct using new before sending it to pthread_create. Don't forget to release it in the sort function.

Log in to reply