用C通过动态分配的整数数组
-
23-08-2019 - |
题
我读传递用C 多维数组的“的例子“在此网站。
有一个很好的例子使用字符数组,并且我从中学到了很多。我想通过创建一个函数来处理一个动态分配的一维整数数组做同样的事情,在那之后,用于处理多维整数数组创建另一个功能。我知道如何做到这一点作为一个返回值的函数。但是,在这个应用程序,我需要做的是参数列表的功能上。
就像在我上面提到的例子中,我想将指针传递到一个整数数组的函数,随着元件的“NUM”数一起(或“行”和“col”为2D阵列功能等)。我得到了其他例子的重新设计版本,在这里,但我不能得到这个工作,尽量为我可能(的代码,新的或修改,从示例行,被标记)。有谁知道如何解决这个问题?
#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)
是1)
不隶属于 StackOverflow