2017-03-15 91 views
-1

我需要編寫一個程序,其中有兩個字段的結構:整數和字符串。接下來,我需要編寫一個動態分配此結構的函數,並將int和string作爲參數傳遞給分配的結構。該函數還將返回指向新建結構的指針。該程序的第二個元素應該是以struct指針作爲參數的函數,然後在屏幕上打印所有文件,然後釋放struct的內存。這是我能想到的最好的。一個結構的動態內存分配

#include <stdio.h> 
#include <stdlib.h> 

struct str{ 
    int num; 
    char text[20]; 
}; 

struct str* return_address(int *num, char *text){ 
    struct str* new_struct=malloc(sizeof(struct str)); 
    new_struct->num=num; 
    new_struct->text[20]=text; 
    return new_struct; 
}; 

void release(struct str* s_pointer){ 
    printf("%d %s", s_pointer->num, s_pointer->text); 
    free(s_pointer); 
}; 



int main() 
{ 
    struct str* variable=return_address(1234, "sample text"); 
    release(variable); 

    return 0; 
} 
+0

問題是什麼? – sergej

+0

我無法讓這個程序工作。即使編譯它崩潰。 –

+0

我猜,'new_struct-> text [20] = text;'不是你想要的 –

回答

0
  1. 你的陣列是非常小的,還它不是動態的。如果您正在使用malloc()進行分配,爲什麼不動態分配所有內容?
  2. 您不能分配給數組。
  3. num成員,我想這是爲了存儲「字符串」的長度,正在分配一個指針,這不是你顯然想要的。此外,行爲只在非常特殊的情況下定義,當你將一個指針指向一個整數時,編譯器應該警告你,除非你關閉了警告。

也許你想要這個,

struct string { 
    char *data; 
    int length; 
}; 

struct string * 
allocate_string(int length, const char *const source) 
{ 
    struct string *string; 
    string = malloc(sizeof *string); 
    if (string == NULL) 
     return NULL; 
    string->length = strlen(source); 
    // Make an internal copy of the original 
    // input string 
    string->data = malloc(string->length + 1); 
    if (string->data == NULL) { 
     free(string); 
     return NULL; 
    } 
    // Finally copy the data 
    memcpy(string->data, source, string->length + 1); 
    return string; 
} 

void 
free_string(struct string *string) 
{ 
    if (string == NULL) 
     return; 
    free(string->data); 
    free(string); 
}