-2

I'm trying to change certain values of a struct pointer.

struct gtaVars_s {
    int godmode;
};

struct gtaVars_s *gtaVars;

void test() {
     gtaVars->godmode = 1;
}

Why does test() fail?

I've tried changing the -> to . but that only gave me errors.

Also I've read various articles about structs but none of them seem to give me an answer about this specific problem.

Appel Flap
  • 261
  • 3
  • 23

1 Answers1

1

Why does test() fail?

test() seems not to be called from main() or one of the called functions from main(), which is required by the C syntax.

I've tried changing the -> to . but that only gave me errors.

That is because you attempt to access a structure object by a pointer. If you use a pointer to access contents of an object of a structure, only -> is allowed.

Why I said "attempt"?

Because you never allocated memory for the structure pointed to by gtaVars in the provided example, so it shall fail in either case.


What you need to do is for example to allocate memory via malloc() and also call test() from main().

Don´t forget to free() dynamically allocated memory to deallocate the memory previously allocated by malloc().

I also passed the pointer as parameter instead of to use a global pointer regarding readability and maintenance:

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

struct gtaVars_s {
    int godmode;
};

void test(struct gtaVars_s *);

int main(void)
{
   struct gtaVars_s *gtaVars = malloc(sizeof(*gtaVars));
   test(gtaVars);

   printf("godmode is %d.",gtaVars->godmode);

   free(gtaVars);
}

void test(struct gtaVars_s *gtaVars) {
     gtaVars->godmode = 1;
}

Output:

godmode is 1.

Personal side notation:

Hasn´t GTA:V already enough available mod-menus with god mode? :-)

  • I appreciate the example, that explains and helps a lot in my journey to learn C. About your personal side notation, I see you're a man of culture for knowing what this is about. – Appel Flap May 08 '20 at 18:26