sprintf

there are two errors at the lines 4 and 5: invalid conversion from 'const char*'
to 'char' [-fpermissive]
1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>
int main() {
char s1[21];
char s2="Ciao";
char s3="pippo";
int age=24;
sprintf (s1, "%s %s ho %d anni", s2, s3, age);
// Scrivo su s1 attraverso la sprintf
// Ora s1 contiene la stringa "Ciao pippo ho 24 anni"
printf("%s",s1);
return 0;
}
Yes, there are! You are trying to assign a const char* to a character. A character can only hold one char.
And your buffer is too small.

The resultant string "Ciao pippo ho 24 anni" is exactly 21 chars long, which is the size of your buffer. The problem is that you also need space for the null terminator as it's a C-string!

You could increase the size of buffer by one, but stack memory space isn't that cramped.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h>
#include <string.h>

int main() {
    char s1[256]; // plenty of space
    const char* s2="Ciao";
    const char* s3="pippo";
    int age=24;

    int lenOutput = sprintf(s1, "%s %s ho %d anni", s2, s3, age);
    
    int lenString = strlen(s1);

    // Scrivo su s1 attraverso la sprintf
    // Ora s1 contiene la stringa "Ciao pippo ho 24 anni"
    printf("%s\n", s1); // now with \n
    printf("len output %d chars\n", lenOutput );
    printf("len string %d chars\n", lenString );  
  
    return 0;
}


Andy

PS indenting is cool!
Last edited on
ok thank you very much, now it goes
Topic archived. No new replies allowed.