繁体   English   中英

打印char *某些输出时控制台停止

[英]Console stops when printing the char *some output

我正在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);

读取控制台输入并将其存储在内存中(从password地址开始)。

  • 问:那个地址是什么?

  • A.指向char( password )的指针。

  • 问:指向char的指针占用多少内存?

  • 答:4字节或8字节(取决于您使用的是32位还是64位系统)。

  • 问:如果输入“ sdfjsdjksdhfjjksdjfh”,将从password的地址开始写入多少个字节?

  • A.21。

因此,您正在将额外的13或17个字节的密码写入...什么内存? 我们不知道,但是我们可以可靠地说它已被程序的某些代码占用,因为用垃圾覆盖自己的程序将导致它在正常结束之前的某个时间停止工作。

解? 查找有关使用C进行编程的好书并学习基础知识。 如果失败,请至少阅读scanf文档 ,包括示例代码。

暂无
暂无

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

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