gpt4 book ai didi

c - 在 C 中传递动态分配的整数数组

转载 作者:行者123 更新时间:2023-11-30 16:05:29 25 4
gpt4 key购买 nike

我在本网站上阅读了有关“Passing multi-dimensional arrays in C ”的示例。

这是一个使用 char 数组的很好的例子,我从中学到了很多东西。我想通过创建一个函数来处理动态分配的一维整数数组来完成同样的事情,然后创建另一个函数来处理多维整数数组。我知道如何将其作为函数的返回值。但在这个应用程序中,我需要在函数的参数列表上执行此操作。

就像我上面提到的示例一样,我想将指向整数数组的指针以及元素数量“num”(或二维数组函数的“row”和“col”)传递给函数, ETC。)。我在这里得到了另一个示例的修改版本,但我无法让它工作,尽我所能尝试(标记了该示例中新增或修改的代码行)。有谁知道如何解决这个问题吗?

#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;
}

关于c - 在 C 中传递动态分配的整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/894604/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com