2017-01-07 107 views
0

我在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; 
} 

回答

0

static char* password;聲明一個指向char的指針。只是 的指針。它沒有指向任何地方的指針,也沒有爲它指定任何內存。

scanf("%s", &password); 

讀取控制檯輸入並將其存儲在地址password的內存中。

  • 問:什麼是在該地址? A.指向char的指針(password)。

  • Q.指向char的指針佔用了多少內存?

  • 答:4個字節或8個字節(取決於您是否在32位或64位系統中)。

  • Q.如果輸入「sdfjsdjksdhfjjksdjfh」,您將從password的地址開始寫多少個字節?

  • A. 21.

所以你寫額外的13或17個字節的密碼到......什麼內存?我們不知道 知道,但我們可以肯定地說它被你的程序的一些代碼 所佔用,因爲用自己的垃圾覆蓋你自己的程序會導致它在 停止工作,在它自然結束之前的某個時間。

解決方案?查找a good book about programming in C 並瞭解基礎知識。否則,至少要讀取包括示例代碼的documentation of scanf, 。

相關問題