[英]Read access violation when using %s format specifier
我一直在嘗試編寫一個將字符串作為輸入的程序,並且 output 將是用莫爾斯電碼編寫的相同字符串,但是在使用帶有 *(mors + i) 的 %s 格式說明符時出現讀取訪問沖突。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning(disable : 4996)
void code(char litery[], const char* mors) {
char arr[256];
printf("string to be coded:\n");
fgets(arr, 256, stdin);
for (int counter = 0; counter < strlen(arr); ++counter) {
if (arr[counter] == ' ') {
printf(" ");
}
int i;
for (i = 0; i < 36; ++i) {
if (arr[counter] == litery[i]) {
printf("%s", *(mors + i));
break;
}
}
}
}
int main() {
char litery[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};
const char* mors[] = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.", "-----" };
code(litery, *mors);
}
您的代碼中的兩個主要問題 -
首先,在這里您傳遞mors
字符串數組的第一個字符串 -
code(litery, *mors);
*mors
與more[0]
相同,即在這里您將指針指向的字符串傳遞給第0
個索引,即字符串".-"
。 相反,您應該傳遞整個mors
數組。
它應該是
code(litery, mors);
^^^^
並且您還必須修改code()
function 的第二個參數的類型以接收mors
字符串數組,如下所示
void code(char litery[], const char** mors)
^^
其次,不要將arr[i]
與litery[i]
進行比較,而應將counter
索引處的arr
數組元素與litery[i]
進行比較
if (arr[counter] == litery[i]) {
^^^^^^^
我在他的代碼中指出,當我發布這個答案時,OP 已經編輯了問題並糾正了Second
問題。
額外的,
當用戶輸入並按下ENTER
鍵時, fgets()
將換行符視為有效字符並將其包含在用戶給出的輸入字符串中。 在處理之前從輸入緩沖區arr
中刪除尾隨換行符,如下所示:
arr[strcspn(arr, "\n")] = 0;
你給我們的代碼有很多問題。 我不知道從哪里開始,但我將跳過所有解釋,這是您的工作代碼,但我不喜歡使用您的輸入風格和 memory 管理:P
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning(disable : 4996)
void code(const char** litery[], const char** mors) {
char arr[256];
printf("string to be coded:\n");
fgets(arr, 256, stdin);
for (int counter = 0; counter < strlen(arr); ++counter) {
if (arr[counter] == ' ') {
printf(" ");
}
int i;
for (i = 0; i < 36; ++i) {
if (arr[counter] == litery[i]) {
printf("%s", (mors[i]));
break;
}
}
}
}
int main() {
const char* litery[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};
const char* mors[] = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.", "-----" };
code(&litery, &mors);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.