简体   繁体   English

从 integer 数组构建一个字符串(字符指针)

[英]Build a string (char pointer) from an integer array

I am doing an assignement that requires me to build a string from a matrix of integer (in a certain way, not the point of this question).我正在做一个作业,要求我从 integer 的矩阵中构建一个字符串(以某种方式,不是这个问题的重点)。 the string has to be a char pointer.字符串必须是 char 指针。

My code is as follows我的代码如下

void funcMatrix(int *matrix, int rows, int columns, char* outBuffer)
{
    int j,i;
    int element =0;
     
    for (i = 0; i < rows; ++i) 
    {
        for (j = 0; j < columns; ++j) 
        {
            malloc(sizeof(matrix[(i * columns) + j]));
            sprintf(outBuffer + (element++),"%d", matrix[(i * columns) + j]);
        }
    }
}

For a matrix对于矩阵

{{ 3, 8},
{  7, 12},
{  0, 10} };

outBuffer should be 38712010 but my code prints 3871010 (because it taking 1 digit from 12) outBuffer应该是38712010但我的代码打印3871010 (因为它从 12 中取 1 位)

how can I solve this please?请问我该如何解决? I am stcuk我被困住了

Idealy I need 3, 8, 7, 12, 0, 10理想情况下我需要 3、8、7、12、0、10

The problem is that you are overwriting the already written digits again!问题是您再次覆盖了已经写入的数字!

How many digits will the number 12 need?数字 12 需要多少位数? And how many digits do you advance your pointer?你的指针前进了多少位?

The safest way to handle this is using the result of sprintf function, which is the number of bytes it wrote (not including the terminating null character):处理此问题的最安全方法是使用sprintf function 的结果,这是它写入的字节数(不包括终止 null 字符):

element += sprintf(outBuffer + element, "%d", matrix[i * columns + j]);

I personally would additionally prefer to use pointers:我个人更喜欢使用指针:

// char* ob = outBuffer;
// actually, we don't even need that one, we do not reuse the parameter
// itself afterwards anyway, so we can simply move that one:

outBuffer += sprintf(outBuffer, "%d", matrix[i * columns + j]);

Furthermore I recommend providing buffer size as well, which helps preventing writing beyond its bounds:此外,我还建议提供缓冲区大小,这有助于防止写入超出其范围:

void funcMatrix
(
    int *matrix, int rows, int columns, char* outBuffer, size_t bufferSize
)
{
    // ...
        int num = snprintf(outBuffer, bufferSize, "%d", matrix[i * columns + j];
        //         ^
        outBuffer += num;
        bufferSize -= num;
    // ...
}

For starters this declaration of the function对于初学者,function 的声明

void funcMatrix(int *matrix, int rows, int columns, char* outBuffer);

does not make a sense.没有意义。

As your matrix is interpreted as a one-dimensional array then there is no need to split the total number of elements in the array into the number of rows and the number of columns because you could call the function like由于您的矩阵被解释为一维数组,因此无需将数组中的元素总数拆分为行数和列数,因为您可以调用 function 之类的

funcMatrix( matrix, rows * columns, outBuffer );

That is the function could have only three parameters.也就是说 function 只能有三个参数。

As the array matrix is not being changed within the function then the corresponding parameter should be declared with the qualifier const .由于数组矩阵在 function 中没有被更改,因此应使用限定符const声明相应的参数。

If the matrix may not have negative numbers then its element type should have the type unsigned int.如果矩阵可能没有负数,则其元素类型应为 unsigned int 类型。 Otherwise either you need also to output the minus sign for negative numbers or write the code such a way that it will ignore the minus sign.否则,您还需要 output 负数的减号,或者编写代码使其忽略减号。

This statement with a memory allocation此语句与 memory 分配

malloc(sizeof(matrix[(i * columns) + j]));

does not make a sense because the returned value is not used.没有意义,因为没有使用返回的值。 So the only effect of the statement is a memory leak.因此该语句的唯一影响是 memory 泄漏。

As a number in the matrix can contain more than one digit then this expression由于矩阵中的数字可以包含多个数字,因此此表达式

sprintf(outBuffer + (element++),"%d", matrix[(i * columns) + j]);
                    ^^^^^^^^^^^         

is in general incorrect.一般是不正确的。

The function can look the following way as it is shown in the demonstrative program below. function 可以如下面的演示程序所示。

#include <stdio.h>
#include <stdlib.h>

size_t total_numbers_length( const unsigned int a[], size_t n )
{
    const int Base = 10;
    
    size_t length = 0;
    
    for ( size_t i = 0; i < n; i++ )
    {
        unsigned int value = a[i];

        do
        {
            ++length;
        } while ( value /= Base );
    }
    
    return length;
}

char * fill_string_from_array( char *buffer, const unsigned int *a, size_t n )
{
    for ( char *p = buffer; n-- ; )
    {
        int  offset = sprintf( p, "%u", *a++ );
        
        if ( offset  <= 0 ) break;
        else ( p += offset );
    }
    
    return buffer;
}

int main(void) 
{
    unsigned int a[] = { 3, 8, 7, 12, 0, 10 };
    const size_t N = sizeof( a ) / sizeof( *a );

    char *buffer = malloc( total_numbers_length( a, N ) + 1 );
    
    if ( buffer )
    {
        puts( fill_string_from_array( buffer, a, N ) );
    }
    
    free( buffer );
    
    return 0;
}

The program output is程序 output 是

38712010

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM