malloc dynamic array in dynamic array of structs

前端 未结 3 1020
情书的邮戳
情书的邮戳 2021-01-26 00:30
typedef struct {
    char *word;
} STR;

int main()
{
    STR *arr=(STR*)malloc(5*sizeof(*arr));
    STR[2].word=(char*)malloc(200*sizeof(char));
    STR[2].word=(char*)         


        
3条回答
  •  佛祖请我去吃肉
    2021-01-26 00:59

    #include 
    #include 
    
    
    typedef struct{
        char *word;
    }STR;
    
    int main(){
        STR *arr=(STR*)malloc(5*sizeof(STR));
        arr[2].word=(char*)malloc(200*sizeof(char));
        if(realloc(arr[2].word, 400*sizeof(char))==NULL){
            /* increasing char array size from 200 to 400 failed. 200 char array was unchanged */
            printf("increasing array size not OK\n");
        }
        else{
            printf("increasing array size OK\n");
        }
        free(arr[2].word);
        free(arr);
        return 0;
    }
    

提交回复
热议问题