用随机数字和字母初始化c中的2d矩阵

用随机数字和字母初始化c中的2d矩阵,c,arrays,pointers,double,C,Arrays,Pointers,Double,提供了这个双指针。它应该指向什么,但我不确定它应该指向什么。任何见解或解释都会非常有用。我试着查找双指针并理解,例如,如果你有一个字符列表,你可以使用类似*单词的东西,如果你想要一个句子,你可以使用**句子来指向单词。但我不知道这是怎么延续下去的 typedef struct square { int i; char c; } Square; Square** initializeMatrix(void); void printMatrixNumbers(Square**);

提供了这个双指针。它应该指向什么,但我不确定它应该指向什么。任何见解或解释都会非常有用。我试着查找双指针并理解,例如,如果你有一个字符列表,你可以使用类似*单词的东西,如果你想要一个句子,你可以使用**句子来指向单词。但我不知道这是怎么延续下去的

typedef struct square
{
    int i;
    char c;
} Square;


Square** initializeMatrix(void);
void printMatrixNumbers(Square**);
void printMatrixLetters(Square**);
void shuffleMatrix(Square**);

Square* initialize1DMatrix(void);
void print1DMatrixLetters(Square*);
void print1DMatrixNumbers(Square*);
void shuffle1DMatrix(Square*);



int main(void)
{
    srand(time(NULL));

    Square** matrix = initializeMatrix();

    while(1)
    {
        printf("Print which set?: ");
        printf("\n1. letters\n2. numbers\n3. shuffle matrix\n4. move to 1D    matrix");
        printf("\n>");
        int choice;
        scanf("%d", &choice);

        if(choice == 1)
        {
            printMatrixLetters(matrix);
        }
        else if(choice == 2)
        {
            printMatrixNumbers(matrix);
        }
        else if(choice == 3)
        {
            shuffleMatrix(matrix);
        }
        else if(choice == 4)
        {
            break;
        }
        else
        {
            printf("Didn't understand that input. Try again\n\n");
        }
    }

    Square* matrix2 = initialize1DMatrix();
    printf("\n\nNow for the 1D array:\n\n");

    while(1)
    {
        int choice;
        printf("Print which set?: ");
        printf("\n1. letters\n2. numbers\n3. shuffle matrix\n4. quit");
        printf("\n>");
        scanf("%d", &choice);

        if(choice == 1)
        {
            print1DMatrixLetters(matrix2);
        }
        else if(choice == 2)
        {
            print1DMatrixNumbers(matrix2);
        }
        else if(choice == 3)
        {
            shuffle1DMatrix(matrix2);
        }
        else if(choice == 4)
        {
            break;
        }
        else
        {
            printf("Didn't understand that input. Try again\n\n");
        }
    }

     return 0;
 }




Square** initializeMatrix()
 {
     //this will be used to randomize the matrix. See below for more info.
     char letters[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',  'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; 


    int row, column;


    Square** matrix;

指针指向内存块。要将一个用作数组,必须分配内存

                    srand(time(NULL));
                    Square.i[row][column]=rand()%10;


             }

     }      




return matrix;
}
我已经创建了一个10平方的数组,ptr指向该数组的第一个平方。通过写入ptr[2]访问第三个正方形

接着是双指针。他们指向其他指针。想象一个矩阵

Square *ptr = malloc(sizeof(Square) * 10)

p1[0]指向指向第一个数组的指针。p1[1]指向第二个,依此类推。为了更好地理解指针,您可以将其视为n维数组,其中n是星的数目。

首先必须定义

然后为矩阵分配内存:

Square **p1;
**p1 = malloc(sizeof(Square) * 10)
*p1 = malloc(sizeof(Square*) * 10)
最后一次更正
此方块。i[行][列]=rand()%10

矩阵[行][列].i=rand()%10

好的,很明显,您需要帮助使用/引用动态分配的内存来理解C的第一部分,所以让我们看一下基础知识。但是,在我们看代码之前,让我们先谈谈如何编译它。您需要在编译时启用警告,然后在考虑代码完成之前消除所有警告。这些警告是用来帮助你的。在使用
gcc
时,至少要启用
-Wall-Wextra
,您可以在其他编译器中检查等效项。您的编译字符串将类似于:

matrix=malloc(sizeof(quare)* ROWS*COLUMNS);
-g
将生成用于使用
gcc
进行调试的符号。调试完成后,您需要将
-g
替换为所需的优化级别
0
(默认为零)或
1、2、3、fast
。您使用大写字母
-O
(哦,不是零)指定选项(例如
-O3
-Ofast
(gcc 4.6及更新版本))

现在,了解如何构建代码,让我们看看如何编写代码。首先,在C中,没有二维数组。只有几种方法可以模拟二维阵列的索引。使用指针数组进行键入时(例如,
Square**matrix
),模拟2D数组的方法是声明并分配指针数组以键入
Square

gcc -Wall -Wextra -g -o square square.c
Square **matrix = NULL;
matrix = calloc (ROWS, sizeof *matrix);
这将声明
指向
Square*
类型矩阵的指针数。然后,为每个指针分配一块内存,以容纳所需数量的
struct Square

gcc -Wall -Wextra -g -o square square.c
Square **matrix = NULL;
matrix = calloc (ROWS, sizeof *matrix);
您可以创建一个helper函数来分配/检查并返回指向新内存块的指针,以保持代码整洁

注2:分配和验证内存块后,您有责任(1)。保留指向该内存块起始地址的指针,以便(2)。当您不再需要该内存块时,可以释放该内存块

对于
1D
数组,事情要简单得多,只需为所需的
Square
类型的数量分配存储。例如:

matrix = calloc (ROWS, sizeof *matrix);
if (!matrix) {
    fprintf (stderr, "%s() error: virtual memory exhausted.\n", __func__);
    exit (EXIT_FAILURE);
}
通过创建允许2D数组类型索引引用相邻数组中任何位置的逻辑,也可以通过此分配模拟2D数组。(看起来像是
matrix[row*ROWS+col]
where
0 2
模拟2D阵列编号为:
299   713   762   909   504   705   697   846
600   735   239     2   870   258   998   155
819    88   649   688   921   890     3   657
418    52   761   739    17   612   159   664
340   264   454   848    49   345   179   359
747   958   523   845   398   259   928   240
380   963   808   561   253   614   613   733
442   222   740   209   228   697   743   777
打印哪一套
1.信件
2.数字
3.洗牌矩阵
4.退出
> 4
==9866==
==9866==堆摘要:
==9866==在出口处使用:0个块中有0个字节
==9866==总堆使用率:10个alloc,10个free,分配1088字节
==9866==
==9866==所有堆块都已释放--不可能存在泄漏
==9866==
==9866==对于检测到的和抑制的错误计数,请使用:-v重新运行
==9866==错误摘要:来自0个上下文的0个错误(已抑制:来自2的2个)

看。你可以添加字母。没有2D数组,也就是矩阵。
正方形**
不是数组!请不要使用
malloc
和朋友的返回:@Jens Gustedt谢谢你的建议!哦,好的。我明白了。为什么我们需要指向指针?为什么我们不能直接使用指针地址?@Joe,因为其他人ise你不能持有矩阵。矩阵是分层数组,但如果你不保留数组的所有开头,它们彼此独立。想象**正方形像一个垂直数组,每个框包含一个指针,每个框中有一个指向水平数组的箭头。谢谢!这个正方形[行][列].i=rand()%10、 仍然得到与以前相同的错误:在“[”之前需要标识符。为什么?抱歉,请更正将“Square”更改为“matrix”。感谢您的注释不要强制执行
malloc
的返回。它只不过是一个内存地址。它没有
'type'
。正确的分配是
matrix=malloc>(行*sizeof*矩阵)
然后
矩阵[i]=malloc(列*sizeof**矩阵)
。然后分配
矩阵[i][j]
matrix = calloc (ROWS, sizeof *matrix);
if (!matrix) {
    fprintf (stderr, "%s() error: virtual memory exhausted.\n", __func__);
    exit (EXIT_FAILURE);
}
matrix = calloc (ROWS * COLS, sizeof *matrix);
void print1DMatrixAs2DNumbers (Square *matrix)
{
    if (!matrix) return;

    int row, col;

    printf ("\n simulated 2D array numbers are:\n\n");
    for (row = 0; row < ROWS; row++) {
        for (col = 0; col < COLS; col++)
            printf ("  %4d", matrix[row * ROWS + col].i);
        putchar ('\n');
    }
    putchar ('\n');
}
while (1) {
    ...
    matrix++;
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define ROWS 8
#define COLS 8

typedef struct square
{
    int i;
    char c;
} Square;

Square **initializeMatrix (void);
void printMatrixNumbers (Square**);
void printMatrixLetters (Square**);
void shuffleMatrix (Square**);

Square *initialize1DMatrix (void);
void print1DMatrixLetters (Square*);
void print1DMatrixNumbers (Square*);
void shuffle1DMatrix (Square*);

int main (void)
{
    srand (time (NULL));

    Square **matrix = initializeMatrix();

    while (1)
    {
        int choice;
        printf ("\nPrint which set?: \n\n"
                " 1. letters\n"
                " 2. numbers\n"
                " 3. shuffle matrix\n"
                " 4. move to 1D matrix\n"
                " > ");
        scanf ("%d", &choice);

        if(choice == 1)         printMatrixLetters (matrix);
        else if(choice == 2)    printMatrixNumbers (matrix);
        else if(choice == 3)    shuffleMatrix (matrix);
        else if(choice == 4)    break;
        else printf("Didn't understand that input. Try again\n");
    }

    Square *matrix2 = initialize1DMatrix();
    printf ("\nNow for the 1D array:\n\n");

    while (1)
    {
        int choice;
        printf ("\nPrint which set?: \n\n"
                " 1. letters\n"
                " 2. numbers\n"
                " 3. shuffle matrix\n"
                " 4. quit\n"
                " > ");
        scanf ("%d", &choice);

        if(choice == 1)         print1DMatrixLetters (matrix2);
        else if(choice == 2)    print1DMatrixNumbers (matrix2);
        else if(choice == 3)    shuffle1DMatrix (matrix2);
        else if(choice == 4)    break;
        else printf("Didn't understand that input. Try again\n");
    }

    /* free simulated 2D matrix */
    size_t i;
    for (i = 0; i < ROWS; i++)
        free (matrix[i]);
    free (matrix);

    /* free matrix2 */
    free (matrix2);

    return 0;
}

Square **initializeMatrix ()
{
    /* unless you can't have a null-terminator, this is fine */
    char letters[] = "abcdefghijklmnopqrstuvwxyz"; 
    int row, col;

    Square **matrix = NULL;

    /* allocate ROWS number of pointers to struct Square 
     * 'calloc' allocates and initializes NULL, you must then
     * validate your allocation by checking the return.
     */
    matrix = calloc (ROWS, sizeof *matrix);
    if (!matrix) {
        fprintf (stderr, "%s() error: virtual memory exhausted.\n", __func__);
        exit (EXIT_FAILURE);
    }

    /* allocate COLS number of struct Square and validate */
    for (row = 0; row < ROWS; row++)
    {
        matrix[row] = malloc (COLS * sizeof **matrix);

        if (!matrix) {
            fprintf (stderr, "%s() error: virtual memory exhausted.\n", 
                    __func__);
            exit (EXIT_FAILURE);
        }

        for (col = 0; col < COLS; col++)
        {
            /* fill i with random number between 0 - 999 */
            matrix[row][col].i = rand() % 1000;

            /* fill c with random letter 'a-z' */
            matrix[row][col].c = letters[rand() % 26];
        }
    }

    return matrix;
}

Square *initialize1DMatrix ()
{
    /* unless you can't have a null-terminator, this is fine */
    char letters[] = "abcdefghijklmnopqrstuvwxyz"; 
    int i;

    Square *matrix = NULL;

    /* allocate memory for ROWS * COLS struct Square
     * and validate
     */
    matrix = calloc (ROWS * COLS, sizeof *matrix);

    if (!matrix) {
        fprintf (stderr, "%s() error: virtual memory exhausted.\n", 
                    __func__);
        exit (EXIT_FAILURE);
    }

    for (i = 0; i < ROWS * COLS; i++)
    {
        /* fill i with random number between 0 - 999 */
        matrix[i].i = rand() % 1000;

        /* fill c with random letter 'a-z' */
        matrix[i].c = letters[rand() % 26];
    }

    return matrix;
}

void printMatrixNumbers (Square **matrix)
{
    if (!matrix) return;

    int row, col;

    printf ("\n simulated 2D array numbers are:\n\n");
    for (row = 0; row < ROWS; row++) {
        for (col = 0; col < COLS; col++)
            printf ("  %4d", matrix[row][col].i);
        putchar ('\n');
    }
    putchar ('\n');
}

void printMatrixLetters (Square **matrix)
{
    if (!matrix) return;

    int row, col;

    printf ("\n simulated 2D array letters are:\n\n");
    for (row = 0; row < ROWS; row++) {
        for (col = 0; col < COLS; col++)
            printf ("  %4c", matrix[row][col].c);
        putchar ('\n');
    }
    putchar ('\n');
}

void shuffleMatrix (Square **matrix)
{
    if (!matrix) return;

    fprintf (stderr, "%s() warning: not yet implemented.\n", __func__);
}

void print1DMatrixNumbers (Square *matrix)
{
    if (!matrix) return;

    size_t i;

    printf ("\n matrix2 numbers are:\n\n");
    for (i = 0; i < ROWS * COLS; i++)
        printf ("  matrix2[%2zu] : %4d\n", i, matrix[i].i);
    putchar ('\n');
}

void print1DMatrixLetters (Square *matrix)
{
    if (!matrix) return;

    size_t i;

    printf ("\n matrix2 letters are:\n\n");
    for (i = 0; i < ROWS * COLS; i++)
        printf ("  matrix2[%2zu] : %c\n", i, matrix[i].c);
    putchar ('\n');
}

void shuffle1DMatrix (Square *matrix)
{
    if (!matrix) return;

    fprintf (stderr, "%s() warning: not yet implemented.\n", __func__);
}
gcc -Wall -Wextra -o bin/square square.c
$ ./bin/square

Print which set?:

 1. letters
 2. numbers
 3. shuffle matrix
 4. move to 1D matrix
 > 2

 simulated 2D array numbers are:

   180   468   335   205   480   606    40   276
   360   581   824   731    59   827   573   708
   837    18   557   109   234   348   255    54
   527   479    60   174   891   799   868   922
    35   230   867   335   406   375   660   629
   416   243   670   948   123   377   607    48
   943   291   617   263    14    37   419   565
   126   664   578   357   712    44   738    17


Print which set?:

 1. letters
 2. numbers
 3. shuffle matrix
 4. move to 1D matrix
 > 1

 simulated 2D array letters are:

     l     a     f     q     l     e     x     y
     x     p     y     w     p     w     c     t
     u     c     h     g     l     q     a     t
     n     m     a     p     v     s     f     l
     i     d     l     l     x     j     r     z
     q     u     t     j     x     p     p     e
     s     o     s     e     c     q     s     c
     d     c     k     p     p     p     j     c


Print which set?:

 1. letters
 2. numbers
 3. shuffle matrix
 4. move to 1D matrix
 > 4

Now for the 1D array:


Print which set?:

 1. letters
 2. numbers
 3. shuffle matrix
 4. quit
 > 2

 matrix2 numbers are:

  matrix2[ 0] :  371
  matrix2[ 1] :  844
  matrix2[ 2] :  287
  matrix2[ 3] :   69
  matrix2[ 4] :   98
  matrix2[ 5] :  327
  matrix2[ 6] :  125
  matrix2[ 7] :  706
  matrix2[ 8] :   54
  matrix2[ 9] :  400
  ...
  matrix2[59] :  504
  matrix2[60] :  655
  matrix2[61] :  604
  matrix2[62] :  583
  matrix2[63] :  597


Print which set?:

 1. letters
 2. numbers
 3. shuffle matrix
 4. quit
 > 1

 matrix2 letters are:

  matrix2[ 0] : f
  matrix2[ 1] : h
  matrix2[ 2] : u
  matrix2[ 3] : r
  matrix2[ 4] : a
  matrix2[ 5] : u
  matrix2[ 6] : b
  matrix2[ 7] : f
  matrix2[ 8] : y
  matrix2[ 9] : e
  ...
  matrix2[60] : a
  matrix2[61] : u
  matrix2[62] : z
  matrix2[63] : h


Print which set?:

 1. letters
 2. numbers
 3. shuffle matrix
 4. quit
 > 4
$ valgrind ./bin/square
==9866== Memcheck, a memory error detector
==9866== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==9866== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==9866== Command: ./bin/square
==9866==

Print which set?:

 1. letters
 2. numbers
 3. shuffle matrix
 4. move to 1D matrix
 > 2

 simulated 2D array numbers are:

   299   713   762   909   504   705   697   846
   600   735   239     2   870   258   998   155
   819    88   649   688   921   890     3   657
   418    52   761   739    17   612   159   664
   340   264   454   848    49   345   179   359
   747   958   523   845   398   259   928   240
   380   963   808   561   253   614   613   733
   442   222   740   209   228   697   743   777

<snip>

Print which set?:

 1. letters
 2. numbers
 3. shuffle matrix
 4. quit
 > 4
==9866==
==9866== HEAP SUMMARY:
==9866==     in use at exit: 0 bytes in 0 blocks
==9866==   total heap usage: 10 allocs, 10 frees, 1,088 bytes allocated
==9866==
==9866== All heap blocks were freed -- no leaks are possible
==9866==
==9866== For counts of detected and suppressed errors, rerun with: -v
==9866== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)