c++ pointers & arrays

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;

int width = 100;
int height = 100;

float cam[] = {-1.1,-1.0,1.2};
float D[] = {0.2,0.2,-0.2};
float U[] = {0.0,1.0,0.0};

float* cross(float* v1,float* v2)
{
float el1[] = {(v1[1]*v2[2]-v1[2]*v2[1]),(v1[2]*v2[0]-v1[0]*v2[2]),(v1[0]*v2[1]-v1[1]*v2[0])};
return el1;
}

float* neg3(float* v)
{
float arr[3];
for(int i=0;i<3;i++)
arr[i] = 0.0-(v[i]);

return arr;
}

/*

float* cam_space(float* p)
{
float* e1 = cross(D,U);
float* e2 = cross(D,cross(U,D));
float* e3_n = D;

float ar[4];
ar[0] = e1[0]*p[0]+e1[1]*p[1]+e1[2]*p[2];
ar[1] = e2[0]*p[0]+e2[1]*p[1]+e2[2]*p[2];
ar[2] = -(e3_n[0]*p[0]+e3_n[1]*p[1]+e3_n[2]*p[2]);
ar[3] = p[3];
return ar;
}

*/
float* translate(float* p,float* v)
{

float arr1[3];
for(int i=0;i<=2;i++)
arr1[i] = p[i] + v[i];

return arr1;
}


int main()
{
float* poi;
poi = cam; //undo later

float* nc;
nc = neg3(cam);
cout<<" "<<nc[0]<<" "<<nc[1]<<" "<<nc[2]<<endl;


float arbit[3] = {0.1,0.1,0.1};

float* temp1;
temp1 = translate(poi,arbit);
//float* temp2;
//temp2 = cam_space(temp);

cout<<" "<<nc[0]<<" "<<nc[1]<<" "<<nc[2]<<endl;
cout<<" "<<poi[0]<<" "<<poi[1]<<" "<<poi[2]<<endl;


cout<<" "<<temp1[0]<<" "<<temp1[1]<<" "<<temp1[2]<<endl;
return 0;
}


Problem: As you can see, I am outputting 'nc' twice. But both the values differ. The second time 'nc' is displayed, it actually shows the 'temp1' value, and temp1 actually shows garbage values. Any help?
use [ code ] [ /code ] tags and only show the part that actually matters please. And you might wanna give your variables more meaningful names.
closed account (D80DSL3A)
Your functions are returning a pointer to an array which is local to the function. These local arrays are no longer in scope after the function returns to main.

You should declare the arrays within main then pass a pointer to these arrays to the functions. The functions then just modify the array passed to it. Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

float cam[] = {-1.1,-1.0,1.2};

// this function modifies the array arr that is passed to it
void neg3(float* v, float* arr)
{
    for(int i=0;i<3;i++)
        arr[i] = 0.0-(v[i]);
    return;
}

int main()
{
    float nc[3];// declare this array here, where it will remain in scope.
    neg3(cam, nc);
    cout<<" "<<nc[0]<<" "<<nc[1]<<" "<<nc[2]<<endl;
    
    return 0;
}// end of main() 
Topic archived. No new replies allowed.