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?

4
  • 2
    add the types of arguments in the definition of functions, eg: float *V_new1(float x, float y, float z) { /* ... */ } Commented Mar 31, 2020 at 10:08
  • thank you for that ,i didn't notice,but i still get a warning: function returns address of local variable Commented Mar 31, 2020 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. Commented Mar 31, 2020 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)? Commented Mar 31, 2020 at 10:20

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.