1

I am currently compiling this on Ubuntu and when i compile this program

#include <stdio.h>

struct vector { float x,y,z; };

struct vector V_new2(x,y,z){
    struct vector thenew;
    thenew.x = x;
    thenew.y = y;
    thenew.z = z;
    return thenew;
}

float* V_new1(x,y,z){
    float thenew[3];
    thenew[0] = x;
    thenew[1] = y;
    thenew[2] = z;
    return thenew;
}

int main()
{
 float *v1 = V_new1(5,6,7);
 struct vector v2 = V_new2(1,2,3);
 printf("v1 : (%f,%f,%f)\n",v1[0],v1[1],v1[2]);
 printf("v2 : (%f,%f,%f)\n",v2.x, v2.y, v2.z);
 return 0;
}

I get these messages in the terminal and in another compiler i simply got Segmentation fault after adding the codes inside the main function.

w.c: In function ‘V_new2’:
w.c:5:15: warning: type of ‘x’ defaults to ‘int’ [-Wimplicit-int]
 struct vector V_new2(x,y,z){
               ^~~~~~
w.c:5:15: warning: type of ‘y’ defaults to ‘int’ [-Wimplicit-int]
w.c:5:15: warning: type of ‘z’ defaults to ‘int’ [-Wimplicit-int]
w.c: In function ‘V_new1’:
w.c:13:8: warning: type of ‘x’ defaults to ‘int’ [-Wimplicit-int]
 float* V_new1(x,y,z){
        ^~~~~~
w.c:13:8: warning: type of ‘y’ defaults to ‘int’ [-Wimplicit-int]
w.c:13:8: warning: type of ‘z’ defaults to ‘int’ [-Wimplicit-int]
w.c:18:12: warning: function returns address of local variable [-Wreturn-local-addr]
     return thenew;

How do i fix this?

ichigo14
  • 63
  • 5
  • 2
    add the types of arguments in the definition of functions, eg: `float *V_new1(float x, float y, float z) { /* ... */ }` – pmg Mar 31 '20 at 10:08
  • thank you for that ,i didn't notice,but i still get a warning: function returns address of local variable – ichigo14 Mar 31 '20 at 10:14
  • 2
    You need to study functions in your C programming book. They usually mention the beginner bug of returning a pointer to local variables too. – Lundin Mar 31 '20 at 10:19
  • @ichigo14 That's now a completely diferent issue which would deserve a question on its own. Luckily, there already is one: [Returning an array (Warning: Function returns address of local variable)?](https://stackoverflow.com/q/6804176/2969749) – glglgl Mar 31 '20 at 10:20

1 Answers1

2

float thenew[3]; is local to function as warning explains. You need to allocate memory for it on the heap (float *thenew = malloc(sizeof(float) * 3);, you'll also need #include <stdlib.h>) or use global variable (not recommended).

glglgl
  • 89,107
  • 13
  • 149
  • 217
Shadowchaser
  • 586
  • 4
  • 8