Search code examples
cpointersprogram-entry-point

How to Point and Modify a Global Variable - C Programming


I'm trying to reference global variables in a function called "userval", and then modify those variables based on user input. Do I need to return these variables at the end of my function?

I am attempting to check my code by printing these global variables within the main function. However, I keep getting random characters.

Here is my code below.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// Global Constants
#define MAX_PSWD_LEN 80
char password = 0;
int len = 0;
int upper = 0;
int lower = 0;
int digit = 0;
int special = 0;

int main(int argc, char *argv[]) {
  userval();
  printf(&len);
  printf(&upper);
  printf(&lower);
  printf(&digit);
  printf(&special);

}

int userval() {

printf("Please enter the minimum length of your password: \n");
scanf("%d", &len);
printf("Please enter the minimum number of uppercase letters in your password: \n");
scanf("%d", &upper);
printf("Please enter the minimum number of lowercase letters in your password: \n");
scanf("%d", &lower);
printf("Please enter the minimum number of decimal digit characters in your password: \n");
scanf("%d", &digit);
printf("Please enter the minimum number of special characters in your password: \n");
scanf("%d", &special);

printf("Thank you. \n");

return len, upper, lower, digit, special;
}

Solution

  • That's not how the printf function works.

    The first parameter is a format string. It contains any static text you want to print along with format specifiers for any values you want to print.

    For example, if you want to print only a integer followed by a newline, the format string you would use is "%d\n", where %d is the format specifier for an integer and \n is a newline character.

    Any subsequent parameters are used to fill in the format. In the case of the values you want to print, you would do the following:

    printf("%d\n", len);
    printf("%d\n", upper);
    printf("%d\n", lower);
    printf("%d\n", digit);
    printf("%d\n", special);