cvertexwavefront

C file parser is unable to save proper values


I am trying to load an Wavefront .obj file, but when I run my code it just outputs what seems to be random values. Where in my code did I make a mistake? This is the code from obj.h:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<cglm/cglm.h>

int loadobj(const char* filename, float* vertices, float* normals, float* texturecoords){
   FILE* file = fopen(filename, "r");
    char lineheader[128];
    int res;
    int i = 0;
    float verticesout[24];
    vec3 vertex;
    if(file == NULL){
      printf("Failed to open file!");
        return 1;
    }
    while(1){
        res = fscanf(file, "%s", lineheader);
        if(res == EOF){
         break;
        }
        if(strcmp(lineheader, "v") == 0){
           fscanf(file, "%f %f %f\n", &vertex[0], &vertex[1], &vertex[2]);
           verticesout[i] = vertex[0];
            verticesout[i + 1] = vertex[1];
            verticesout[i + 2] = vertex[2];
         i += 3;
        }
    }
    vertices = verticesout;
    return 0;
}

And here is the code in main.c:

#include<stdio.h>
#include<stdlib.h>
#include<cglm/cglm.h>
#include"obj.h"

int main(){
   float vertices[24];
   float normals[24];
   float texcoords[24];
   loadobj("model.obj", vertices, normals, texcoords);
   int i;
   for(i = 0; i < sizeof(vertices)/sizeof(float); i++){
      printf("%f", vertices[i]);
   }
   printf("\n");
}

Solution

  • The argument vertices will receive a copy of what is passed, so the assignment

    vertices = verticesout;
    

    just before returning is meaningless.

    In this case, you should use memcpy() to copy the contents of buffer to the destination

    memcpy(vertices, verticesout, sizeof(verticesout));
    

    or save the values to the elements of vertices directly instead of saving to verticesout.