Reset C



  • What's the better way?

    1. int *f() {
          int a[2] = {4, 5};
          int *p = a;
          p = (int*)malloc(2 * sizeof(int));
          p[0] = a[0];
          p[1] = a[1];
          return p;
      }
      
    2. void f(int *p)
      {
          // Память по адресу `p` выделена вне функции
          int a[2] = {4, 5};
          p[0] = a[0];
          p[1] = a[1];
      }
      


  • Which option would be preferable to context. If there is already a family of functions (which can also be attributed f(d) In the event of a challenge, it would be preferable to give the first option: int *f()♪ If the family ' s functions are performed with a predetermined memory, it is reasonable to use the second option: void f()♪ In any case, the documentation must describe who is responsible for the release of a memory addressed by the index.

    When comparing the use options, the benefits and minus in both cases can also be seen:

    • Option 1:

      int* ptr = f();
      use(ptr);
      free(ptr);
      
    • Option 2a:

      int* ptr = malloc(...);
      f(ptr);
      use(ptr); 
      free(ptr);
      
    • Option 2b:

      int ptr[] = {...}; 
      f(ptr);
      use(ptr);
      

    The first option clearly requires dynamic memory work. In the second option, a glass or global memory may also be used. Denial malloc/free may generate substantial productivity gains in certain situations.

    Option 1, compared compared to 2b for the user code, will be shorter, as there is no need for clear memory, and variables ptr initiated in place.

    Of the standard cherry functions for the first option, only remembered strdup♪ Though I think there should be more options. But the second type functions are definitely bigger.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2