gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:10:07 25 4
gpt4 key购买 nike

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;


提供了此双指针。它应该指向某个东西,但我不确定它应该指向什么。任何见解或解释都将非常有用。我试过查找双指针并理解,例如,如果您有一个字符列表,则可以使用* word之类的东西,然后从那里如果您想要一个句子,就可以进行***,它指向单词。不确定如何继续下去。

    for(row = 0; row < ROWS; row++)
{


应该做些什么,但是还不确定。这是指针数组获得其自己的元素数组的地方吗?
        }

        for(row = 0; row < ROWS; row++)
{
for(column = 0; column < COLUMNS; column++)
{


在这里,我需要生成随机数字和字母,然后将该数字和字符提供给矩阵。在下面,我在','标记之前得到了预期的标识符或')'。为什么是这样?

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


}

}




return matrix;
}

最佳答案

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

gcc -Wall -Wextra -g -o square square.c


-g将生成用于使用 gcc进行调试的符号。完成调试后,将需要用所需的优化级别 -g(默认值为零)或 0替换 1, 2, 3, fast。您可以使用大写字母 -O(哦,不为零)(例如 -O3-Ofast(gcc 4.6及更高版本))指定选项。

现在知道如何构建代码,让我们看看如何编写代码。首先,在C中,没有2D数组。只有模拟2D阵列索引的方法。当您使用要输入的指针数组(例如 Square **matrix)时,模拟2D数组的方法是声明并分配一个指针数组以输入 Square类型:

Square **matrix = NULL;
matrix = calloc (ROWS, sizeof *matrix);


这将声明 ROWS指向 Square*类型的矩阵的指针数。然后,为每个指针分配一个内存块,以容纳所需数量的 struct Square

for (row = 0; row < ROWS; row++)
{
matrix[row] = malloc (COLS * sizeof **matrix);
...
}


现在,您已声明 ROWS指向 COLS数字类型为 Square的数组的指针的数量。即使不要求任何数组在内存中是连续的,这也允许您模拟2D数组。

注意: calloc用于分配指针。 calloc分配并初始化为 NULL(或 0)。每次分配一块内存时,都需要验证分配是否成功。为此,您每次都要检查 malloccallocrealloc的返回值。例如。:

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


您可以创建一个辅助函数来分配/检查并返回一个指向新内存块的指针,以保持代码整洁。

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

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

matrix = calloc (ROWS * COLS, sizeof *matrix);


您也可以通过简单地创建允许2D数组类型索引引用连续数组中任何位置的逻辑,从此分配中模拟2D数组。 (看起来像 matrix[row*ROWS+col],其中 0 <= row < ROWS)。尽管不是下面示例的一部分,但是如果您确实想从 matrix2模拟2D数组,那么出于完整性考虑,您可以按以下方式实现打印数字部分:

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');
}


注2中的(1.)是什么意思?这意味着您必须特别注意不要执行以下操作:

while (1) {
...
matrix++;
}


完成循环后,什么指向原始分配的内存块的开始?没有。如果没有起始地址,则无法再释放该内存。如果您遇到这种情况,请创建一个指向矩阵的指针,然后在循环中使用它。 (例如 Square *p = matrix;然后 while (1) {... p++;}

这些是执行您要尝试执行的操作的基础知识。剩下的只是语法和整理程序逻辑。是的,我知道您也需要帮助。

下面是一个实现您的代码的示例。它旨在向您展示如何将各个部分放在一起,而不是为您做。 C是一种非常优雅且灵活的低级语言,它可以对机器提供强大的功能和控制力,而汇编语言除外。有与任何语言相关的学习曲线,C没什么不同。但是,与其他高级语言不同,C使您可以灵活地执行语法允许的任何事情。函数中没有内置保护措施,可以防止在尝试分配失败后超出数组末尾写入或写入内存区域。学习C语言,您有责任学习该水平的C语言,以防止遇到可预见的问题,而不是获得力量。

#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


内存泄漏/错误检查

在您可以动态分配内存的任何代码中,必须使用内存错误检查程序。对于Linux, valgrind是通常的选择。滥用内存块有许多微妙的方法,它们可能导致真正的问题,这是没有理由不这样做。每个平台都有类似的内存检查器。它们易于使用。只需通过它运行程序即可。

$ 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)

关于c - 用随机数和字母初始化c中的2d矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33024118/

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