如何字符串存储到在一个结构中声明的字符指针 [英] How to store a character string into a character pointer declared in a structure

查看:114
本文介绍了如何字符串存储到在一个结构中声明的字符指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的code:

 #include<stdio.h>



    struct p{

           char* d;
           };

    typedef struct p* pt;

    int main(){
        pt opt;
        opt=(pt)malloc(sizeof(struct p));

        scanf("%s",(opt->d));


        printf("%s",opt->d);



        getch();

        return 0;

        }

每次我运行它,它接受并打印字符串不错,但出现错误。
在调试它告诉,有一个段错误,但不指向它在哪里?
到底哪里出问题了,它似乎是相当正确的。

Everytime I run it , it accepts and prints the string fine but an error occur. On debugging it tells that there is a segmentation fault but doesn't points to where it is? What is going wrong , It's seems to be fairly correct.

推荐答案

scanf函数把扫描的字符串到字符缓冲区。但在你的code你的字符指针没有指向它应该指向一个缓冲区中的所有事情

the scanf put the scanned string to a char buffer. but in your code your char pointer is not pointing to any thing it should be pointed to a buffer

如果您的gcc> 2.7,可以使用MS%。这将允许scanf函数为指针分配内存

If your gcc> 2.7, you can use "%ms". this will allow to scanf to allocate memory for your pointer

scanf("%ms",(opt->d));

这篇关于如何字符串存储到在一个结构中声明的字符指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆