문제
나는 예제를 읽었다 "c"이 사이트에서.
숯불 어레이를 사용하는 좋은 예이며, 나는 그것으로부터 많은 것을 배웠습니다. 동적으로 할당 된 1 차원 정수 배열을 처리하기위한 함수를 만들어서 동일한 작업을 수행하고, 그 후 다차원 정수 배열을 처리하기위한 다른 기능을 만듭니다. 함수에 대한 반환 값으로 수행하는 방법을 알고 있습니다. 그러나이 응용 프로그램에서는 인수 목록에서 함수에 대한 수행해야합니다.
위에서 언급 한 예에서와 마찬가지로 정수 배열에 대한 포인터를 함수에 전달하고 요소 "num"(또는 2D 배열 함수 등의 "행"및 "col"수와 함께 전달하고 싶습니다. ). 여기서는 다른 예제의 재 작업 버전을 얻었지만이 작업을 수행 할 수는 없습니다. 시도한대로 시도합니다 (해당 예제에서 새롭거나 수정 된 코드 라인이 표시됨). 누구든지 이것을 해결하는 방법을 아는 사람이 있습니까?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ELEMENTS 5
void make(char **array, int **arrayInt, int *array_size) {
int i;
char *t = "Hello, World!";
int s = 10; // new
array = malloc(ELEMENTS * sizeof(char *));
*arrayInt = malloc(ELEMENTS * sizeof(int *)); // new
for (i = 0; i < ELEMENTS; ++i) {
array[i] = malloc(strlen(t) + 1 * sizeof(char));
array[i] = StrDup(t);
arrayInt[i] = malloc( sizeof(int)); // new
*arrayInt[i] = i * s; // new
}
}
int main(int argc, char **argv) {
char **array;
int *arrayInt1D; // new
int size;
int i;
make(array, &arrayInt1D, &size); // mod
for (i = 0; i < size; ++i) {
printf("%s and %d\n", array[i], arrayInt1D[i]); // mod
}
return 0;
}
해결책
이 코드에는 많은 문제가 있습니다. 다음을 살펴보십시오.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ELEMENTS 5
/*
* A string is an array of characters, say char c[]. Since we will be creating
* an array of those, that becomes char *(c[]). And since we want to store the
* memory we allocate somewhere, we must be given a pointer. Hence char
* **(c[]).
*
* An int doesn't require a complete array, just int i. An array of those is
* int i[]. A pointer to those is then int *(i[]).
*/
void
make(char **(chars[]), int *(ints[]), size_t len)
{
static char hw[] = "Hello, World!";
size_t i = 0;
/*
* Allocate the memory required to store the addresses of len char arrays.
* And allocate the memory required to store len ints.
*/
*chars = malloc(len * sizeof(char *));
*ints = malloc(len * sizeof(int));
/* Fill each element in the array... */
for (i = 0; i < ELEMENTS; i++) {
/* ... with a *new copy* of "Hello world". strdup calls malloc under
* the hood! */
(*chars)[i] = strdup(hw);
/* ...with a multiple of 10. */
(*ints)[i] = i * 10;
}
}
int
main(void)
{
/* A string c is a character array, hence char c[] or equivalently char *c.
* We want an array of those, hence char **c. */
char **chars = NULL;
/* An array of ints. */
int *ints = NULL;
size_t i = 0;
/* Pass *the addresses* of the chars and ints arrays, so that they can be
* initialized. */
make(&chars, &ints, ELEMENTS);
for (i = 0; i < ELEMENTS; ++i) {
printf("%s and %d\n", chars[i], ints[i]);
/* Don't forget to free the memory allocated by strdup. */
free(chars[i]);
}
/* Free the arrays themselves. */
free(ints);
free(chars);
return EXIT_SUCCESS;
}
다른 팁
여기에 행 크기가 누락되었습니다.
arrayInt[i] = malloc( sizeof(int)); // new
다음과 같아야합니다.
arrayInt[i] = malloc( row_len * sizeof(int)); // new
주어진 문자열의 길이를 행 크기로 사용하기 전에 strlen(t)+1
효과는 동일하지만 괄호 안에 있어야합니다. sizeof(char)
IS 1)
제휴하지 않습니다 StackOverflow