Pregunta

I lee el ejemplo en " pasar matrices multidimensionales en C "en este sitio.

Es un gran ejemplo utilizando matrices de carbonilla, y he aprendido mucho de él. Quisiera hacer lo mismo mediante la creación de una función para manejar una matriz de enteros unidimensional asignada dinámicamente, y después de eso, crear otra función para el manejo de una matriz de enteros multi-dimensional. Yo sé cómo hacerlo como un valor de retorno a una función. Pero en esta solicitud que tengo que hacer en la lista de argumentos de la función.

Al igual que en el ejemplo he mencionado anteriormente, me gustaría pasar un puntero a una matriz de enteros a una función, junto con el número de elementos "num" (o "fila" y "col" para una función de matriz 2D , etc.). Tengo una nueva versión del otro ejemplo aquí, pero no puedo conseguir que esto funcione, mucho que lo intentaba (líneas de código que son nuevos o modificados, de este ejemplo, están marcados). ¿Alguien sabe cómo resolver esto?

#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;
}
¿Fue útil?

Solución

Hay un montón de problemas en ese código. Echar un vistazo a lo siguiente:

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

Otros consejos

Te estas perdiendo el tamaño de una fila aquí:


arrayInt[i] = malloc( sizeof(int)); // new

debería ser algo como:


arrayInt[i] = malloc( row_len * sizeof(int)); // new

donde antes estuviera usando longitud de cadena dada como el tamaño de la fila (también strlen(t)+1 debe haber entre paréntesis, aunque el efecto es el mismo porque es sizeof(char) 1)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top