Home > Software design >  Declare and initialize a character array separately in C language
Declare and initialize a character array separately in C language

Time:12-03

Hi I am trying to make a simple login system with C with the use of character array and this is my first step. I want to separately declare and initialize a character array and I don't know how to do it correctly but I try to make a code, but I receive a warning. warning: assignment to 'char' from 'char *' makes integer from pointer without a cast. I am using CodeBlocks.

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

int main()
{
  char username[25];
  char password[25];

  username[25] = "pyromagne";
  password[25] = "qwerty";

  // char username[25] = "pyromagne"; THIS TWO WORKS DECLARED AND INTITIALIZED TOGETHER
  // char password[25] = "qwerty";

  /* IGNORE THIS, But if there is wrong to this that can produce errors in the future please correct me thanks.
  printf("enter username: ");
  scanf("%s", username);

  printf("enter your password: ");
  scanf("%s", password);
  */

  getch();

  printf("%s\n", username);
  printf("%s\n", password);


  return 0;
}

CodePudding user response:

You are trying to assign string literals to a mutable character array. You can change it to:

char *username = "pyromagne";
char *password = "qwerty";

Or if you will want to change these strings later:

char username[25];
char password[25];
strncpy(username, "pyromagne", sizeof(username));
strncpy(password, "qwerty", sizeof(password));
  • Related