programing

C의 배열에 여러 값 할당

css3 2023. 7. 4. 22:02

C의 배열에 여러 값 할당

이것을 축약된 형태로 할 수 있는 방법이 있습니까?

GLfloat coordinates[8];
...
coordinates[0] = 1.0f;
coordinates[1] = 0.0f;
coordinates[2] = 1.0f;
coordinates[3] = 1.0f;
coordinates[4] = 0.0f;
coordinates[5] = 1.0f;
coordinates[6] = 0.0f;
coordinates[7] = 0.0f;
return coordinates;

비슷한 것coordinates = {1.0f, ...};?

실제로 값을 할당하려면(초기화가 아닌) 다음과 같이 할 수 있습니다.

 GLfloat coordinates[8]; 
 static const GLfloat coordinates_defaults[8] = {1.0f, 0.0f, 1.0f ....};
 ... 
 memcpy(coordinates, coordinates_defaults, sizeof(coordinates_defaults));

 return coordinates; 

이 경우 일반 초기화만 하면 되지만, 선언 후에 초기화할 수 있는 구조로 배열을 묶는 방법이 있습니다.

예:

struct foo {
  GLfloat arr[10];
};
...
struct foo foo;
foo = (struct foo) { .arr = {1.0, ... } };

구식 방법:

GLfloat coordinates[8];
...

GLfloat *p = coordinates;
*p++ = 1.0f; *p++ = 0.0f; *p++ = 1.0f; *p++ = 1.0f;
*p++ = 0.0f; *p++ = 1.0f; *p++ = 0.0f; *p++ = 0.0f;

return coordinates;

사용할 수 있는 항목:

GLfloat coordinates[8] = {1.0f, ..., 0.0f};

그러나 이것은 컴파일 시간 초기화입니다. 현재 표준에서 해당 방법을 사용하여 다시 초기화할 수 없습니다. (비록 다가오는 표준에서 즉시 도움이 되지 않을 수도 있지만).

생각나는 다른 두 가지 방법은 내용이 수정되면 노골적으로 말하는 것입니다.

GLfloat base_coordinates[8] = {1.0f, ..., 0.0f};
GLfloat coordinates[8];
:
memcpy (coordinates, base_coordinates, sizeof (coordinates));

또는 초기화 코드와 유사한 기능을 제공합니다.

void setCoords (float *p0, float p1, ..., float p8) {
    p0[0] = p1; p0[1] = p2; p0[2] = p3; p0[3] = p4;
    p0[4] = p5; p0[5] = p6; p0[6] = p7; p0[7] = p8;
}
:
setCoords (coordinates, 1.0f, ..., 0.0f);

그 타원들을 기억하는 것 (...)는 문자 그대로 코드에 삽입할 항목이 아닌 자리 표시자입니다.

어레이 초기화 방법을 사용했습니다.

#include <stdarg.h>

void int_array_init(int *a, const int ct, ...) {
  va_list args;
  va_start(args, ct);
  for(int i = 0; i < ct; ++i) {
    a[i] = va_arg(args, int);
  }
  va_end(args);
}

라는 식으로 불렸습니다.

const int node_ct = 8;
int expected[node_ct];
int_array_init(expected, node_ct, 1, 3, 4, 2, 5, 6, 7, 8);

C99 어레이 초기화는 다음과 같습니다.

const int node_ct = 8;
const int expected[node_ct] = { 1, 3, 4, 2, 5, 6, 7, 8 };

그리고.configure.ac:

AC_PROG_CC_C99

내 개발 상자의 컴파일러는 완벽하게 행복했습니다.서버의 컴파일러에서 다음 문제가 발생했습니다.

error: variable-sized object may not be initialized
   const int expected[node_ct] = { 1, 3, 4, 2, 5, 6, 7, 8 };

그리고.

warning: excess elements in array initializer
   const int expected[node_ct] = { 1, 3, 4, 2, 5, 6, 7, 8 };

각 요소에 대해

예를 들어 다음과 같은 문제에 대해 전혀 불평하지 않습니다.

int expected[] = { 1, 2, 3, 4, 5 };

크기를 확인하고 어레이 이니셜라이저를 지원하는 것보다 vargs 지원이 더 강력하게 작동하는 것이 좋습니다.

https://github.com/wbreeze/davenport/pull/15/files 에서 샘플 코드로 PR 찾기

@paxdiablo의 https://stackoverflow.com/a/3535455/608359 과 관련하여, 나는 그것을 좋아했지만, 초기화 포인터가 배열에 할당된 요소의 수와 동기화되는 횟수를 갖는 것에 대해 불안함을 느꼈습니다.최악의 경우 초기화 포인터가 할당된 길이를 초과합니다.이와 같이 PR의 차이는 다음을 포함합니다.

  int expected[node_ct];
- int *p = expected;
- *p++ = 1; *p++ = 2; *p++ = 3; *p++ = 4;
+ int_array_init(expected, node_ct, 1, 2, 3, 4);

int_array_initmethod는 인수 수가 node_ct보다 적으면 안전하게 정크를 할당합니다.정크 할당은 더 쉽게 검색하고 디버그할 수 있어야 합니다.

맞아요, 거의 다 맞췄어요.

GLfloat coordinates[8] = {1.0f, ..., 0.0f};

프로그램에서 이러한 동일한 작업을 많이 수행하고 있으며 바로 가기를 원하는 경우 가장 간단한 해결 방법은 기능을 추가하는 것일 수 있습니다.

static inline void set_coordinates(
        GLfloat coordinates[static 8],
        GLfloat c0, GLfloat c1, GLfloat c2, GLfloat c3,
        GLfloat c4, GLfloat c5, GLfloat c6, GLfloat c7)
{
    coordinates[0] = c0;
    coordinates[1] = c1;
    coordinates[2] = c2;
    coordinates[3] = c3;
    coordinates[4] = c4;
    coordinates[5] = c5;
    coordinates[6] = c6;
    coordinates[7] = c7;
}

그런 다음 간단히 전화합니다.

GLfloat coordinates[8];
// ...
set_coordinates(coordinates, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f);
typedef struct{
  char array[4];
}my_array;

my_array array = { .array = {1,1,1,1} }; // initialisation

void assign(my_array a)
{
  array.array[0] = a.array[0];
  array.array[1] = a.array[1];
  array.array[2] = a.array[2];
  array.array[3] = a.array[3]; 
}

char num = 5;
char ber = 6;

int main(void)
{
  printf("%d\n", array.array[0]);
// ...

  // this works even after initialisation
  assign((my_array){ .array = {num,ber,num,ber} });

  printf("%d\n", array.array[0]);
// ....
  return 0;
}

언급URL : https://stackoverflow.com/questions/3535410/assign-multiple-values-to-array-in-c