简体   繁体   English

C语言分别声明和初始化一个字符数组

[英]Declare and initialize a character array separately in C language

Hi I am trying to make a simple login system with C with the use of character array and this is my first step.嗨,我正在尝试使用字符数组使用 C 制作一个简单的登录系统,这是我的第一步。 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 . 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;
}

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) - 1);
strncpy(password, "qwerty", sizeof(password) - 1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM