문제
C 를 전달할 수 있습니 다차원 배열하는 기능으로 하나의 인수할 때 내가 무엇인지 모르는 차원의 배열이 있는 것?
또한 내 다차원의 배열을 포함할 수 있습 형태 이외의 문자열입니다.
해결책
당신이 할 수 있으로 어떤 데이터 유형이 있습니다.단순히 그것은 포인터 포인:
typedef struct {
int myint;
char* mystring;
} data;
data** array;
하지만 당신은 여전히 malloc 변수,그리고 그것을 얻을 조금 복잡:
//initialize
int x,y,w,h;
w = 10; //width of array
h = 20; //height of array
//malloc the 'y' dimension
array = malloc(sizeof(data*) * h);
//iterate over 'y' dimension
for(y=0;y<h;y++){
//malloc the 'x' dimension
array[y] = malloc(sizeof(data) * w);
//iterate over the 'x' dimension
for(x=0;x<w;x++){
//malloc the string in the data structure
array[y][x].mystring = malloc(50); //50 chars
//initialize
array[y][x].myint = 6;
strcpy(array[y][x].mystring, "w00t");
}
}
코드를 할당 구조와 비슷한-전화하는 것을 잊지 마세 무료()에 모든 것을 당신 것 malloc 로 당 된!(또한,에서 강력한 응용 프로그램야 체크의 반환 malloc().)
지금의 말을 전달하려는 이 기능이 있습니다.계속 사용할 수 있습니다 두 배의 포인터이기 때문에,당신은 아마 하고 싶 조작에서,데이터 구조,지 않은 포인터를 포인터 데이터 구조
int whatsMyInt(data** arrayPtr, int x, int y){
return arrayPtr[y][x].myint;
}
이 함수를 호출과:
printf("My int is %d.\n", whatsMyInt(array, 2, 4));
출력:
My int is 6.
다른 팁
전달이 명시적 첫 번째 요소를 가리키는 포인터 배열 차원으로 별도의 매개 변수입니다.예를 들어,손잡이를 임의로 크기의 2 차원 배열의 int:
void func_2d(int *p, size_t M, size_t N)
{
size_t i, j;
...
p[i*N+j] = ...;
}
는 것으로 불
...
int arr1[10][20];
int arr2[5][80];
...
func_2d(&arr1[0][0], 10, 20);
func_2d(&arr2[0][0], 5, 80);
같은 원리를 적용한다 더 높은 차원 배열:
func_3d(int *p, size_t X, size_t Y, size_t Z)
{
size_t i, j, k;
...
p[i*Y*Z+j*Z+k] = ...;
...
}
...
arr2[10][20][30];
...
func_3d(&arr[0][0][0], 10, 20, 30);
를 선언할 수 있습니다 당신의 기능:
f(int size, int data[][size]) {...}
컴파일러는 다음을 수행한 모든 포인터 연산을 위해 당신입니다.
참고는 차원을 크기를 나타나야 합니다 기 배 자체입니다.
GNU C 할 수 있습에 대한 인수 선언을 전달(경우를 전달해야 할 필요가 있는 치수 후 배):
f(int size; int data[][size], int size) {...}
첫 번째 차원만 전달할 수 있습으로 인수,너무 쓸모를 위한 C 컴파일러(도에 대한 sizeof,에 적용될 때 통해 전달되는 배열로 인수은 항상 치료는 포인터로 첫 번째 요소는).
int matmax(int **p, int dim) // p- matrix , dim- dimension of the matrix
{
return p[0][0];
}
int main()
{
int *u[5]; // will be a 5x5 matrix
for(int i = 0; i < 5; i++)
u[i] = new int[5];
u[0][0] = 1; // initialize u[0][0] - not mandatory
// put data in u[][]
printf("%d", matmax(u, 0)); //call to function
getche(); // just to see the result
}