簡體   English   中英

C編程:char指針的scanf無法正常工作

[英]C programming: scanf for char pointer not working

我有一個程序可以接收用戶輸入的教室和時間。 課堂輸入存儲在char *教室內部,時間存儲在int時間內部。 但是,當我運行該程序時,鍵入教室后,按Enter鍵時該程序停止。 “請輸入時間:”的printf沒有出來。 為什么會這樣呢?

void option1()
{
  char* classroom; 
  int time;        

  printf("Please enter the classroom: ");
  scanf_s("%s", &classroom); 

  printf("Please enter the time: ");
  scanf_s("%d", &time);
}

感謝幫助 :)

正如我已經評論過的,此代碼段中存在很多錯誤:

  • scanf_sscanf ,它需要其他大小參數。 我建議不要使用它。
  • 切勿在scanf()僅使用"%s" ,您需要指定字段寬度以防止緩沖區溢出。 (這與scanf_s()不同,因為緩沖區大小是那里的一個附加參數。)
  • 您嘗試通過無處指向的指針( classroom )寫入數據,您需要分配內存! (通過將其設置為數組或通過調用malloc() )。

糾正了這些錯誤的代碼段可能如下所示:

void option1()
{
  char classroom[128];
  int time;        

  printf("Please enter the classroom: ");
  scanf("%127s", classroom);
  // field width is one less than your buffer size,
  // because there will be a 0 byte appended that terminates the string!

  printf("Please enter the time: ");
  scanf("%d", &time);
}

創建變量作為指針並為其分配內存,或者分配char數組並將其傳遞給scanf。

//Use of array
char classroom[10];
scanf("%9s", classroom); 

//Use of heap
char* classroom = malloc(10 * sizeof(*classroom));
scanf("%9s", classroom); 
//Use your variable classroom here, when done, call free to release memory.
free(classroom);

此處的字符串長度為9以防止緩沖區溢出和越界寫入。 數組的大小為10元素。

使用scanf代替scanf_s ,為char指針分配內存,並且不使用& ,它已經是指針。 請參見下面的示例:

#include <stdio.h>
#include <stdlib.h>

int main()
{
  int time;        
  char* classroom; 
  classroom = malloc(sizeof(char) * 1024);

  if(classroom == NULL)
  {
    fprintf(stderr, "Failed to allocate memory!\n");
    exit(1);
  }

  printf("Please enter the classroom: ");
  scanf("%s", classroom); 

  printf("Please enter the time: ");
  scanf("%d", &time);


  printf("\nClassroom: %s\n", classroom);
  printf("Time: %d\n", time);

  free(classroom); //Free the memory

  return 0;
}

scanf系列函數將格式字符串指定的數據讀入作為參數提供的變量。

這些函數不會為字符串變量分配存儲空間! 在沒有分配內存的情況下為scanf提供可變的classroom ,將使scanf嘗試將數據放置在內存中的未定義位置。 這可以導致任何類型的行為,通常稱為未定義行為

因此,您必須首先為字符串變量分配存儲,例如:

char*classroom= malloc(1024);

現在您可以使用它調用scanf:

scanf_s("%s", classroom);

請注意,由於char指針的行為就像一個數組(即,它指向char的數組),因此您不必使用運算符&的地址。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM