На главную Наши проекты:
Журнал   ·   Discuz!ML   ·   Wiki   ·   DRKB   ·   Помощь проекту
ПРАВИЛА FAQ Помощь Участники Календарь Избранное RSS
msm.ru
Модераторы: Qraizer, Hsilgos
  
> C99 - динамические массивы?
    Привет, все!
    Лектор заявил ц99 поддерживает динамические массивы.
    В смысле, такой код возможен:

    void f(int n)
    {
    char arr[n];
    arr[2] = 1;
    // etc
    }
    main()
    {
    f(2);
    return 0;
    }

    А в каком это компилере?
      ни в каком!
      он имел в виду new[],delete []
      void f(int n)
      {
      char *arr=new char[n]
      arr[2] = 1;
      // etc
      delete []arr;
      }
      main()
      {
      f(2);
      return 0;
      }


      Добавлено в
      Ба недосмотрел!
      Нумерация в С99 от 0 до n-1. То есть в arr[2] от ты можешь обращаться 0 до 1. И arr[2]=1 у тя будет ошибкой.
      ЗЫ
      Надеюь нормально разъяснил, бо как-то полохо с формулировками.
      И лучше юзай стандартный шаблон std::Vector
        Ну, так какой конкретно копилер работает с этим?
        VC5 и Борланд не могу заставит это скушать.
          никакой.
          в стандарте нет такого
          char a[n]; где n - переменная.
          n может быть только константой, известной на момент компиляции. при этом такой массив размещается в области данных или стека проргаммы.

          динамичесикй это
          char* aa=new char[n];
          ...
          delete[] aa;
          и он будет размещаться в куче.

          они (эти два способа) совсем разные, и по размещению, и по реализации. разве чтор аботать в программе с ними можно похожеsmile.gif тк в обоих случаях переменная aa имеет тип char*
            В стандарте С99 это наз-ся variable-length array (VLA).
            Вот например оттуда

                  [#7] EXAMPLE 3 In this example,  the  size  of  a  variable-
                  length array is computed and returned from a function:

                          size_t fsize3 (int n)
                          {
                                  char b[n+3];       // Variable length array.
                                  return sizeof b;   // Execution time sizeof.
                          }
                          int main()
                          {
                                  size_t size;
                                  size = fsize3(10); // fsize3 returns 13.
                                  return 0;
                          }

            Компилер, любой поддерживающий стандарт С99, у мня например Intel C 7.0... только там по дефолту С99 disabled, так что нужно явно указывать в параметрах компиляции -Qc99
              Там есть и определение(§6.7.5.2):
              Цитата
              ... If the size is * instead of being an expression, the array type is a variable length array type of unspecified size, which can only be used in declarations with function prototype scope;(122) such arrays are nonetheless complete types. If the size is an integer constant expression and the element type has a known constant size, the array type is not a variable length array type; otherwise, the array type is a variable length array type.
              If the size is an expression that is not an integer constant expression: if it occurs in a declaration at function prototype scope, it is treated as if it were replaced by *; otherwise, each time it is evaluated it shall have a value greater than zero. The size of each instance of a variable length array type does not change during its lifetime.
              ...
              Array objects declared with the static or extern storage-class specifier cannot have a variable length array (VLA) type.
              extern int n;
              int A[n]; // invalid: file scope VLA
              extern int (*p2)[n]; // invalid: file scope VM
              int B[100]; // valid: file scope but not VM
              void fvla(int m, int C[m][m]); // valid: VLA with prototype scope
              void fvla(int m, int C[m][m]) // valid: adjusted to auto pointer to VLA
              {
                typedef int VLA[m][m]; // valid: block scope typedef VLA
                struct tag {
                    int (*y)[n]; // invalid: y not ordinary identifier
                    int z[n]; // invalid: z not ordinary identifier
                };
                int D[m]; // valid: auto VLA
                static int E[m]; // invalid: static block scope VLA
                extern int F[m]; // invalid: F has linkage and is VLA
                int (*s)[m]; // valid: auto pointer to VLA
                extern int (*r)[m]; // invalid: r has linkage and points to VLA
                static int (*q)[m] = &B; // valid: q is a static block pointer to VLA
              }
                А вот в С++ это не поддерживается, как я понимаю?
                  Там для этого есть оператор new
                  1 пользователей читают эту тему (1 гостей и 0 скрытых пользователей)
                  0 пользователей:


                  Рейтинг@Mail.ru
                  [ Script execution time: 0,0547 ]   [ 15 queries used ]   [ Generated: 6.07.25, 10:26 GMT ]