我正在尝试编写我认为会很简单的程序,但我遇到了一些问题。当我尝试将字符串读入 char 指针时,出现段错误,但仅在代码的某些部分出现。我觉得这是我读取字符串的方式的问题,但我没有得到比段错误更多的信息。
这是我的代码:
#include <stdio.h>
#include <string.h>
int main() {
char *Q_or_U;
char *E_or_P;
int entry;
int rc;
while(1) {
printf("Would you like to query or update? (q/u): ");
rc = scanf("%s", Q_or_U);
if (rc != 1) break;
printf("received %s\n", Q_or_U);
if (strcmp(Q_or_U, "q") == 0 || strcmp(Q_or_U, "Q") == 0) {
//execution fine in this block
printf("Which entry would you like to query? ");
rc = scanf("%d", &entry);
if (rc != 1) break;
printf("received %d\n", entry);
}
else if (strcmp(Q_or_U,"u") == 0 || strcmp(Q_or_U, "U") == 0) {
//misbehaving
printf("Would you like to encrypt that message? (y/n): ");
rc = scanf("%s", E_or_P); //segmentation fault
if (rc != 1) break;
printf("received %s", E_or_P);
}
}
}
段错误总是在尝试将字符串读入我的变量 E_or_P 时发生,我错过了什么? (我是 C 的新手)。
最佳答案
你的两个变量都是指针,但它们指向宇宙中的随机字节。当您写入那个地方时,导致崩溃只是运气。
你需要让它们指向一些有效的内存才能被允许在那里写入。
一种方法是使用malloc (char *Q_or_U = malloc(30);
),另一种是用内存声明它们(char Q_or_U[30];
or所以)。
关于c - 将字符串读入 char * 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42730047/