This question already has an answer here:
这个问题在这里已有答案:
- Why do I get a segmentation fault when writing to a string initialized with “char *s” but not “char s[]”? 16 answers
- 为什么在写入用“char * s”而不是“char s []”初始化的字符串时会出现分段错误? 16个答案
I am attempting to store a string in a variable declared as char *name[2];
. I am using scanf()
to obtain the value from user input. This is my code so far and its currently not working:
我试图将一个字符串存储在一个声明为char * name [2];的变量中。我使用scanf()从用户输入中获取值。这是我的代码到目前为止,它目前无法正常工作:
#include <stdio.h>
#include <stdlib.h>
int main()
{ char *name[2];
scanf("%s",name[0]);
printf("%s",name[0]);
return 0;
}
2 个解决方案
#1
2
You haven't allocated any storage for the actual strings - char *name[2]
is just an array of two uninitialised pointers. Try:
您没有为实际字符串分配任何存储空间 - char * name [2]只是两个未初始化指针的数组。尝试:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char name[2][80];
scanf("%s", name[0]);
printf("%s", name[0]);
return 0;
}
or, if it really does need to be char *name[2]
, then you can allocate memory dynamically:
或者,如果它确实需要是char * name [2],那么你可以动态分配内存:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *name[2];
name[0] = malloc(80); // allocate memory for name[0] (NB: name[1] left uninitialised)
scanf("%s", name[0]);
printf("%s", name[0]);
free(name[0]); // free memory allocated for name[0]
return 0;
}
#2
0
char *name[2];
You have 2 pointers which are of type char
你有2个char类型的指针
Allocate memory to the pointer using malloc()
or any of its family membres.
使用malloc()或其任何系列元素将内存分配给指针。
name[0] = malloc(20);
#1
2
You haven't allocated any storage for the actual strings - char *name[2]
is just an array of two uninitialised pointers. Try:
您没有为实际字符串分配任何存储空间 - char * name [2]只是两个未初始化指针的数组。尝试:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char name[2][80];
scanf("%s", name[0]);
printf("%s", name[0]);
return 0;
}
or, if it really does need to be char *name[2]
, then you can allocate memory dynamically:
或者,如果它确实需要是char * name [2],那么你可以动态分配内存:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *name[2];
name[0] = malloc(80); // allocate memory for name[0] (NB: name[1] left uninitialised)
scanf("%s", name[0]);
printf("%s", name[0]);
free(name[0]); // free memory allocated for name[0]
return 0;
}
#2
0
char *name[2];
You have 2 pointers which are of type char
你有2个char类型的指针
Allocate memory to the pointer using malloc()
or any of its family membres.
使用malloc()或其任何系列元素将内存分配给指针。
name[0] = malloc(20);