0

I am a fresh man of C++, I would like to make a template function. I have met an issue with the return value of templates. the code is like this

#include <iostream>
#include <cmath>
#include <gsl/gsl_rng.h>
#define pi 3.1415926535

using namespace std;


template <class T>
T cpradius(T a,T b,T p, int n)
{

    const gsl_rng_type *R;
    gsl_rng *r;

    gsl_rng_env_setup();
    R = gsl_rng_default;
    r = gsl_rng_alloc(R);

    T p1[n],p3[n],p2 ;
    T radius[n] ;
    for (int i = 0; i<n; i++)
    {
        p1[i] = gsl_rng_uniform(r);
        p2 += p1[i];
    }

    for (int j = 0; j<n; j++)
    {
        p3[j] = p1[j]/p2;
        radius[j] = sqrt(p3[j]*a*b*p/pi);
        //cout <<  radius[j] << endl; 
    }

    return radius[n];
}

int main(){

    double r[30] = {0};
    r[30] = cpradius(30.0,30.0,0.6,30);
    for (int i = 0;i<30;i++){
        cout << r[i] <<endl;
    }
    return 0;
}

then, compile it:

g++ -Wall -I/usr/local/include/ tst3.cpp -lgsl -lgslcblas

the result is 1 colum, 30 zero :

0
0
0
...
0

it seems the initial array not updated, does anybody help me? thank you!

default
  • 11,485
  • 9
  • 66
  • 102
Kylxyz
  • 29
  • 9
  • valid array indexes are `[0, n-1]`, therefore `radius[n]` and `r[30]` invoke undefined behaviour. –  Feb 21 '13 at 14:41

1 Answers1

2

This has nothing to do with templates. An array with 30 elements has elements at the indizes 0..29. You store something in r[30] which is off limits.

Further, you are creting arrays of nonconst length (p1, p3 and radius), which ist not valid C++. From your return I assume you want to return the whole array, containing 30 values. What you ar doing is returning the 31st (!) value, or at least you try by accessing result[n]. This is undefined behavior, meaning anything can happen: nothing, a crash, anything you might expect, an online pizza order to your address...

It seems you still need some basic understanding about C++ arrays and how to deal with them.

PS: As a first hint, std::vector might be exaclty what you are looking for, since it's the C++ way to handle variable length arrays.

PS2: Don't use #define for constants. Use constant variables of a fixed type instead. It will never hurt but sometimes save you some painful debugging.

Arne Mertz
  • 24,171
  • 3
  • 51
  • 90
  • Thank u buddy, yes, it seems I have a lonnnnnnnnnnnng way to travel. I think you can image a guy just turn to C++ from MATLAB, but, still I wanna work with C++, glad to talk, thank u again! – Kylxyz Feb 21 '13 at 15:18
  • Maybe it's not that long - it's only that similar code has slightly different syntax and very different semantics. The things you are trying to do are not that hard to master :-) Good luck! – Arne Mertz Feb 21 '13 at 15:42