c - 指针相关查询

标签 c pointers

伙计们,我对指针的疑问很少。请帮助解决它们

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/

相关文章:

c - 从根指针指向的二叉搜索树中删除数据

c - 链接列表元素未显示

c++ - 如何将变量从变量传递到指针结构对象?

c++ - 如何保持指向存储在 vector 中的结构的指针有效?

c - 在 C 中退出循环后丢失变量值

c - 为什么按下回车键后会显示输入内容?

c++ - ANSI C 89 和 C++ 支持的 C 有什么区别?

c# - String to Char* 无内存泄漏

c++ - 将参数传递给 _beginthread 函数

代码的调用流程 - C