用于接受和打印字符串的非常小的 c 程序中的分段错误



为什么在执行printf((时出现分割错误?

#include <stdio.h>
int main()
{
char* a ;
printf("Enter name: ");
scanf("%s",a);
printf("%sn",a);
return 0;
}

有两种方法可以做到这一点。一个是将输入存储为char *另一个是将其存储到数组中。

如何作为字符进行操作 *

#include <stdio.h>
#include <stdlib.h>
int main(void) {
char *a = malloc(sizeof(char) * 20); // You can change 20 to the number of letters you need
printf("Enter name: ");
scanf("%s", a);
printf("%sn", a);
free(a); // Don't forget to free. If you malloc memory, you must free it
return 0;
}

如何作为数组进行操作

#include <stdio.h>
#include <stdlib.h>
#define ARRAY_SIZE      20 // You can change 20 to the number of letters you need
int main(void) {
char a[ARRAY_SIZE];
printf("Enter name: ");
fgets(a, ARRAY_SIZE, stdin); // Scanning in the letters into the array
printf("%s", a);
return 0;
}

您必须使用 malloc 或将其声明为数组来初始化变量a

char a[20];
char * a = (char *) malloc(20);

最新更新