2012-06-05 32 views
2

我:分配值,爲所有元素現場

#include <stdio.h> 

struct DVD { 
    char *movie_title; 
    int minutes; 
    float price; 
}; 

void display_struct(struct DVD *ptr); 

int 
main() 
{ 
    struct DVD movies[10]; 
    movies[0].movie_title = "I Am Legend"; //Don't want to do this 
} 

void 
display_struct(struct DVD *ptr) 
{ 
    printf("%s\n%i\n%f\n", ptr->movie_title, ptr->minutes, ptr->price); 
} 

我想分配10部電影給我在一個單獨的語句結構的數組。這可能嗎?謝謝!

回答

7

在這樣的一個單一的聲明?

main() 
{ 
    struct DVD movies[10] = { 
     { .movie_title = "I Am Legend", 
      .minutes = 101, 
      .price = 9.99 
     }, 
     { .movie_title = "Hancock", 
      .minutes = 103, 
      .price = 5.99 
     }, 
     { .movie_title = "MIB3", 
      .minutes = 106, 
      .price = 9.49 
     } 
    }; 
} 

如果你想避免所有的字段名稱:

main() { 
    struct DVD movies[10] = { 
     { "I Am Legend", 101, 9.99 }, 
     { "Hancock",  103, 5.99 }, 
     { "MIB3",  106, 9.49 } 
    }; 
} 
+1

快速打字那裏! –

+1

請注意,如果在您的編譯器中不可用,「dot-field-name =」是C. 的一個相對較新的添加,您可以使用不帶字段名稱的值。 – abelenky

+0

如果您按順序初始化,您甚至不需要指示符(並且它在C99之前工作)。 –

2
#include <stdio.h> 

struct DVD { 
    char *movie_title; 
    int minutes; 
    float price; 
}; 

void display_struct(struct DVD *ptr); 

int main() 
{ 
    struct DVD movies[10] = 
    { 
     { "I am Legend", 90, 4 }, 
     { "Star Wars", 100, 5 }, 
     { "Another Title", 60, 1}, 
     ....... 
    }; 
} 

void display_struct(struct DVD *ptr) 
{ 
    printf("%s\n%i\n%f\n", ptr->movie_title, ptr->minutes, ptr->price); 
}