简体   繁体   中英

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. 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;

1) Allocated the memory for char * d like (Mentioned in above reply)
opt->d = malloc(expected_max_len + 1);

2) Or you can declare buffer with maximum buffer length in structure:
char d[MAX_LENGTH];

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

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

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

You have to allocate memory for 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.

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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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