-1

I can't figure out why test is not passed properly to test1

#include <Arduino.h>

char *test1;
char *status_reply(char *test) {
        int ans_rel = 1;
        int ans_led = 0;
        int ans_sw = 1;
        sprintf(test,"%d%d%d",ans_rel,ans_sw,ans_led);
        Serial.println(test);
}

void setup() {
        Serial.begin(9600);
        status_reply(test1);
        Serial.println(test1);
}

void loop() {
        // put your main code here, to run repeatedly:
}
guyd
  • 1,033
  • 2
  • 16
  • 51

1 Answers1

2

This is not about Arduino. It is C. You have only a pointer to char now. You must allocate memory for the c-string.

char test1[128];

If you pass pointer to sprintf, the function will write to memory where the pointer points. Something somewhere in memory will be overwritten and the following print will print the string, but later the memory will be used for something else and your c-string disappear.

Juraj
  • 18,037
  • 4
  • 29
  • 49
  • thank you. There's something I'm missing : 1) In any other case if I would init char *test1="hello world" at the beginning, and print it Serial.println(test1) - I would have get proper value. 2) In code here - when I create test inside it does print it as expected, but not passing its value to test2 ? – guyd Aug 22 '18 at 06:48
  • char *test1="hello world" would be a pointer to a global allocated constant c-string and should be const char *test1="hello world". I enhanced the answer. – Juraj Aug 22 '18 at 06:52