gpt4 book ai didi

c - 如何将 1D char 转换为 2D int 数组并将其传递给 int C?

转载 作者:行者123 更新时间:2023-11-30 19:01:47 25 4
gpt4 key购买 nike

对于我的学校项目,我必须将 1D char 数组转换为 2D int 数组,并且必须将此数组发送到另一个函数来处理它。但由于某种原因,我无法正确创建 2D int 数组或将其传递给另一个函数。我需要传递整个数组!我需要使用 malloc 或指针吗?

#include <stdio.h>

void ft_test(char *str,int w,int h)

{
int ct = 0, ct2 = 0, i = 0, j = 0;
int stt[w][h];

//this converts the chars to integers and puts it inside stt arrray
while(str[ct])
{
if (str[ct] == '\n')
{
j = 0;
i++;
}
if (str[ct] == '.')
{
stt[i][j] = 1;
j++;
}
else if (str[ct] == 'o')
{
stt[i][j] = 0;
j++;
}
ct++;
}

/*this is just to display the array but somehow there are errors in the displayed
matrix, some places needs to be 0 but displayed as 1. if you display the matrix
in the while before this, it works. but in this while it doesnt*/
ct = 0;
while (ct < h)
{
ct2 = 0;
while (ct2 < w)
{
printf("%d",stt[ct][ct2]);
ct2++;
}
printf("\n");
ct++;
}
}

int main()
{
int w = 0, ct = 0, h = 0;
char stt[] = ".o.o...o\n........\n...o..o.\n";

//counting width & height while displaying it like a matrix
while (stt[w] != '\n')
w++;
while (stt[ct] != '\0')
{
if (stt[ct] == '\n')
h++;
printf("%c",stt[ct]);
ct++;
}
printf("\n");
ft_test(stt,w,h);
return 0;
}

我没有收到任何错误。但 int 数组的一些变量不正确。我错过了什么?

instead of giving -1 vote why not describe what is wrong with my question so that i can improve it?

最佳答案

您的意思如下。

#include <stdio.h>
#include <string.h>

void ft_test( const char *s, size_t rows, size_t cols )
{
unsigned int a[rows][cols];
memset( a, 0, sizeof( a ) );

for ( size_t i = 0, j = 0; *s != '\0'; ++s )
{
if ( *s == '\n' )
{
j = 0;
++i;
}
else
{
if ( *s == '.' ) a[i][j] = 1;
++j;
}
}

for ( size_t i = 0; i < rows; i++ )
{
for ( size_t j = 0; j < cols; j++ )
{
printf( "%u", a[i][j] );
}
putchar( '\n' );
}
}

int main( void )
{
char s[] = ".o.o...o\n........\n...o..o.\n";

size_t rows = 0, cols = 0;

for ( char *p = s, *q = s; *p; q = p )
{
size_t n;

++rows;

p = strchr( q, '\n' );

if ( p == NULL ) n = strlen( q );
else n = p - q;

if ( cols < n ) cols = n;

p = q + n + 1;
}

ft_test( s, rows, cols );
}

程序输出为

10101110
11111111
11101101

关于c - 如何将 1D char 转换为 2D int 数组并将其传递给 int C?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57274987/

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