简体   繁体   中英

Should I use T foo[X] instead of T *foo if x is know at compile-time?

Assuming this:

struct A
{
    char *a;
        char *b;
}

If I know size of a and b at compile-time is worth effort if I do use a fixed-array-size instead of or will it change nothing? it will save a lot of malloc calls, much of them in a loop and I think it's fastest.

struct A
{
    char a[256];
    char b[32];
};

If you can do everything with the second option that you want to do, then it's a better option. You should avoid dynamic memory allocation unless it's necessary. There are some reasons to go with the first option. The obvious one is that you might have a variable size, but you've indicated that that isn't the case. Here are some other reasons:

  1. You might want to reassign a and b , which can be done with pointers but not arrays.
  2. You might want to be able to efficiently move an A object.

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