Why this code does not work correctly (gives random numbers from memory)?

#include <stdio.h> int fun(int n, ... ){ int *ptr = &n; ptr++; return *ptr; } int main() { printf("%d\n", fun(1, 10)); return 0; } 
  • one
    Naturally. Who taught you how to work with varargs? - Sergey Gornostaev
  • @SergeyGornostaev Internet, so his ... - Anton
  • one
    Take the best tutorial, it definitely will not deceive. Or use official documentation and standards. And to sources on the Internet should be approached with caution. - Sergey Gornostaev
  • @SergeyGornostaev Do not tell me, some time ago there was one student, he is such a textbook, written by his teacher, demonstrated - where this method was imposed as standard ... :( - Harry
  • @Harry what a mess. - Sergey Gornostaev

1 answer 1

 #include <stdarg.h> #include <stdio.h> int fun(int n, ...) { va_list args; va_start(args, n); int i = va_arg(args, int); va_end(args); return i; } int main() { printf("%d\n", fun(1, 10)); return 0; } 
  • Yes, this method was also on the site, it followed right after mine, so I decided to start in order) - Anton