Nuñito Calzada
Nuñito Calzada

Reputation: 1718

sprintf in C (pointer to an array of char elements)

I am a newbie in C, and I want to do something like

    uint8_t message[12];

    message[0] = 0x00;
    message[1] = 0x00;
    message[2] = 0x00;
    message[3] = 0x00;
    message[4] = 0x00;
    message[5] = 0x00;
    message[6] = 0x00;
    message[7] = 0x00;
    message[8] = 0x00;
    message[9] = 0x00;
    message[10] = 0x00;
    message[11] = 0x00;

sprintf(_smess,"AT$SS=%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n",
                            message[0], message[1], message[2], message[3],
                            message[4], message[5], message[6], message[7],
                            message[8], message[9], message[10], message[11]);

But I don't know how to declare the variable _smess, I've tried with char *_smess or uint8_t _smess[12] but I got an error anyway

if a declare char _smess[43]; then I got this error:

Multiple markers at this line
    - incompatible implicit declaration of built-in function 'sprintf' [enabled by 
     default]
    - implicit declaration of function 'sprintf' [-Wimplicit-function-declaration]
    - each undeclared identifier is reported only once for each function it 
     appears in
    - '_smess' undeclared (first use in this function)

Upvotes: 0

Views: 978

Answers (2)

Kumar L
Kumar L

Reputation: 1

int sprintf( char* buffer, const char* format, ... );

each character we have to allocate memory... In your case "AT$SS=" required 6 bytes,
%02x required 2bytes empty space between each charcter required 1byte Total bytes required is 6 + 24 + 11 =41 bytes. Allocate memory by static variable char _smess[41] or dynamic allocation char *_smess = new char[41]; unsigned char will not accepted

Upvotes: 0

dbush
dbush

Reputation: 225827

You know how big the string is based on the format string passed to sprintf (i.e. 42 characters), so declare a char array of at least that size, making sure to leave room for the NUL ('\0') terminator:

char _smess[43];

Edit:

The error "incompatible implicit declaration of built-in function 'sprintf'" is because you didn't #include <stdio.h> at the top of your file.

The "'_smess' undeclared" error is most likely because you didn't define it before it was used. It needs to appear before the sprintf call.

Upvotes: 1

Related Questions