user3602030
user3602030

Reputation: 87

Class in C (not C++)

I've discovered this hack in a website in Spanish (http://trucosinformaticos.wordpress.com/2010/12/12/programacion-orientado-a-objetos-en-c/).

I want create a "class" in C (not C++), but when I compile, I obtain the next errors:

source.c(25): warning C4047: 'function' : 'Car' differs in levels of indirection from 'Car *'
source.c(25): warning C4024: 'changeYears' : different types for formal and actual parameter 1

This is my code:

#include <string.h>

typedef struct Car* Car;

// class Car
// {
        struct Car
        {
            int years;
            //char model[100];
        };


        void changeYears(Car this, int years)
        {
            this->years = years;
        }
// }


int main(void)
{
    Car my_cars[10];
    //nombrar(mis_alumnos[0], "Pepito");
    changeYears(&my_cars[0], 6); // My car has now 6 years

    return 0;
}

Upvotes: 0

Views: 175

Answers (2)

merlin2011
merlin2011

Reputation: 75585

I would agree with @Oli Charlesworth that hiding a pointer behind a typedef is a very easy way to confuse yourself and others.

However, to make your code compile and work, you can just remove the & operator in front of my_cars. You also need to allocate memory for those pointers. I would say the reason why you made this mistake in the first place was that you confused yourself with the pointer hiding.

#include <string.h>

typedef struct Car* Car;

struct Car
{
    int years;
    //char model[100];
};


void changeYears(Car this, int years)
{
    this->years = years;
}


int main(void)
{
    // An array of struct char*
    Car my_cars[10];
    int i;
    for (i = 0; i < 10; i++)
        my_cars[i] = malloc(sizeof(struct Car));
    changeYears(my_cars[0], 6); // My car has now 6 years

    return 0;
}

Here is a more reasonable way to implement this without hiding pointers.

#include <string.h>

typedef struct
{
    int years;
    //char model[100];
} Car;


void changeYears(Car* this, int years)
{
    this->years = years;
}


int main(void)
{
    Car my_cars[10];
    changeYears(&my_cars[0], 6); // My car has now 6 years
    return 0;
}

Upvotes: 5

Peter Varo
Peter Varo

Reputation: 12180

I think this is what you are looking for:

(A much cleaner implementation, of what you want)

CODE:

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

typedef struct
{
    int years;

} Car;


void changeYears(Car *this, int years)
{
    this->years = years;
}


int main(void)
{
    Car *car = malloc(sizeof(Car));
    changeYears(car, 2014);

    printf("car.years = %d\n", car->years);

    free(car);
    return 0;
}

OUTPUT:

car.year = 2014

Upvotes: 1

Related Questions