简体   繁体   English

如何将字符串存储到结构中声明的字符指针中

[英]How to store a character string into a character pointer declared in a structure

This is my 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. 出了什么问题,这似乎是正确的。

You used malloc to allocate space for your structure, but not for the string you want to read in. You need to do that too. 您使用malloc为结构分配了空间,但没有为要读取的字符串分配空间。您也需要这样做。 Here's an example paraphrased from your question: 这是您的问题解释的一个示例:

 pt opt = malloc(sizeof(struct p));
 opt->d = malloc(MAX_STRING_LENGTH);

Yupp, the problem is that you have to allocate memory for char * d; Yupp,问题在于您必须为char * d;分配内存char * d;

1) Allocated the memory for char * d like (Mentioned in above reply) 1)像上面一样在char * d分配内存(在上面的答复中提到)
opt->d = malloc(expected_max_len + 1);

2) Or you can declare buffer with maximum buffer length in structure: 2)或者您可以在结构中声明具有最大缓冲区长度的缓冲区:
char d[MAX_LENGTH];

the scanf put the scanned string to a char buffer. scanf将扫描的字符串放入char缓冲区。 but in your code your char pointer is not pointing to any thing it should be pointed to a buffer 但在您的代码中,您的char指针未指向任何东西,因此应将其指向缓冲区

If your gcc> 2.7, you can use "%ms" . 如果gcc> 2.7,则可以使用"%ms" this will allow to scanf to allocate memory for your pointer 这将允许scanf为指针分配内存

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

You have to allocate memory for char* d; 您必须为char* d;分配内存char* d;

int main(){
    pt opt;
    opt=(pt)malloc(sizeof(struct p));
    opt->d = malloc( sizeof( char )* 80);
    scanf("%s",(opt->d));    //this might overflow

You need pass correct buffer to scanf not just point-to-somewhere pointer. 您需要传递正确的缓冲区以使scanf不仅仅是指向某处的指针。

struct p{
   char* d;
};

typedef struct p* pt;

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

    opt->d = malloc(expected_max_len + 1);

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


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

    free(opt->d);


    getch();

    return 0;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM