Is this normal?


hi,

i'm having strange issue either sprintf or compiler, apparently both string pointers being assigned equal address because point equal content, whereas i'd expect them point different copies of such content.

here's complete code:
code: [select]
unsigned int tempbeepf[5]={440,880,220,110,0};
unsigned int tempbeepd[5]={100,200,300,400,500};

void setup() {
    serial.begin(9600);

    //wrong output. compiler thinks it's acceptable assign strd pointer same address strf points to
    // because strings they're initialized point equal?
    char *strf="    ";
    char *strd="    ";
    (byte i=0;i<5;i++){ 
      sprintf(strf, "%0.4d", tempbeepf[i]);
      sprintf(strd, "%0.4d", tempbeepd[i]);
      serial.println(string("beep "+string(i+1)+": freq="+string(strf)+"hz, duration="+string(strd)+"ms"));
    }

    serial.println();
    //output's good.
    char *strf2="   .";
    char *strd2="    ";
    (byte i=0;i<5;i++){ 
      sprintf(strf2, "%0.4d", tempbeepf[i]);
      sprintf(strd2, "%0.4d", tempbeepd[i]);
      serial.println(string("beep "+string(i+1)+": freq="+string(strf2)+"hz, duration="+string(strd2)+"ms"));
    }

    serial.println();
    //output's too.
    char *strf3=(char*)realloc(strf3, sizeof(char)*4);
    char *strd3=(char*)realloc(strd3, sizeof(char)*4);
    (byte i=0;i<5;i++){ 
      sprintf(strf3, "%0.4d", tempbeepf[i]);
      sprintf(strd3, "%0.4d", tempbeepd[i]);
      serial.println(string("beep "+string(i+1)+": freq="+string(strf3)+"hz, duration="+string(strd3)+"ms"));
    }
}

void loop() {
}


and output:
code: [select]
beep 1: freq=0100hz, duration=0100ms
beep 2: freq=0200hz, duration=0200ms
beep 3: freq=0300hz, duration=0300ms
beep 4: freq=0400hz, duration=0400ms
beep 5: freq=0500hz, duration=0500ms

beep 1: freq=0440hz, duration=0100ms
beep 2: freq=0880hz, duration=0200ms
beep 3: freq=0220hz, duration=0300ms
beep 4: freq=0110hz, duration=0400ms
beep 5: freq=0000hz, duration=0500ms

beep 1: freq=0440hz, duration=0100ms
beep 2: freq=0880hz, duration=0200ms
beep 3: freq=0220hz, duration=0300ms
beep 4: freq=0110hz, duration=0400ms
beep 5: freq=0000hz, duration=0500ms


although experience sprintf limited, i've been using first way of initialization, because read sprintf requires pointer , not fixed array work, , must allocated prior use. thought first way convenient , okay, guess wrong.

yes, in cases constant strings pooled. need allocate storage string variables.
code: [select]
    char strf [4] = "    ";
    char strd [4] = "    ";




Arduino Forum > Using Arduino > Programming Questions > Is this normal?


arduino

Comments