控制台在打印char*some输出时停止



我正在visual studio c++2012中编写简单的程序。我动态地接受一些输入。当在控制台上打印int值时,它工作正常,但打印char*somevariable时,它停止并给出错误program.exe已停止工作。

我的程序就像

#include <stdlib.h>
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int choice;
//char *userName;
static char* password;
static char* firstname;
static char* lastname;
static char* username;
char* name;
printf("n 1.Login");
printf("n 2.register");
printf("nEnter choice");
scanf("%d", &choice);
printf("n%d", choice);
switch (choice) {
case 1:
printf("n Enter username :");
scanf("%s", &username);
printf("n Enter username :");
scanf("%s", &password);
break;
case 2:
printf("n Enter Firstname :");
scanf("%s", &firstname);
printf("n Enter lastname :");
scanf("%s", &lastname);
printf("n Enter username :");
scanf("%s", &username);
printf("n Enter username :");
scanf("%s", &password);
printf("n");
//name = "sdfjsdjksdhfjjksdjfh";
printf("%s", password);
break;
default:
printf("n Wrong Choice Entered..");
break;
}
getchar();
return 0;
}

我假设您指的是行

printf("%s",password);

这行应该是

printf("%p", (void*) &password);

这在这个问题的公认答案中得到了很好的解释。是否将格式说明符更正为打印指针(地址)?

static char* password;声明了一个指向char的指针。只是指针。它不会把指针指向任何地方,也不会为位于.的点分配任何内存

scanf("%s", &password);

读取控制台输入并将其存储在从CCD_ 2的地址开始的存储器中。

  • Q。那个地址是什么?

  • A。指向字符(password)的指针。

  • Q。指向字符的指针占用多少内存?

  • A。4字节还是8字节(取决于您是在32位还是64位系统中)。

  • Q。如果您输入"sdfjsdjksdhfjjksdjfh",从password的地址开始,您将写入多少字节?

  • A。21.

所以您正在将额外的13或17个字节的密码写入。。。什么记忆?我们没有知道,但我们可以可靠地说,它被你的程序,因为用垃圾覆盖你自己的程序会导致在它自然结束之前的某个时候停止工作。

解决方案?找一本关于C语言编程的好书学习基础知识。如果做不到这一点,至少要阅读scanf的文档,包括示例代码。

最新更新