伙计们,我对指针的疑问很少。请帮助解决它们
char a[]="this is an array of characters"; // declaration type 1
char *b="this is an array of characters";// declaration type 2
问题1:这两种声明有什么区别?
printf("%s",*b); // gives a segmentation fault
printf("%s",b); // displays the string
问题2:我不知道它是如何工作的
char *d=malloc(sizeof(char)); // 1)
scanf("%s",d); // 2)
printf("%s",d);// 3)
问题3 分配给指针c的字节数是多少? 当我尝试输入一个字符串时,它只需要一个单词而不是整个字符串。为什么会这样?
char c=malloc(sizeof(char)); // 4)
scanf("%c",c); // 5)
printf("%c",c);// 6)
question.4 当我尝试输入一个字符时,为什么会抛出一个段错误?
提前致谢.. 等待你们的回复..
最佳答案
printf("%s",*b); // gives a segmentation fault
printf("%s",b); // displays the string
%s 需要一个指向字符数组的指针。
char *c=malloc(sizeof(char)); // you are allocating only 1 byte aka char, not array of char!
scanf("%s",c); // you need pass a pointer to array, not a pointer to char
printf("%s",c);// you are printing a array of chars, but you are sending a char
你需要这样做:
int sizeofstring = 200; // max size of buffer
char *c = malloc(sizeof(char))*sizeofstring; //almost equals to declare char c[200]
scanf("%s",c);
printf("%s",c);
question.3 how many bytes are being allocated to the pointer c? when i try to input a string, it takes just a word and not the whole string. why so ?
在您的代码中,您只分配了 1 个字节,因为 sizeof(char) = 1byte = 8bit,您需要分配 sizeof(char)*N,N 是您的“字符串”大小。
关于c - 指针相关查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13520026/