How to use malloc and snprintf() to create formatted a new string in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SIZE 256

int main()
{
    const char *str = "C Programming";
    
    char *p = malloc(sizeof(char) * SIZE);        
    
    snprintf(p, SIZE, "%s - %d %f\n", "C Programming", 17, 3.14f);
    
    printf("%s\n", p);    
    
    free(p);  
    
    return 0;
}
  
  
  
/*
run:
  
C Programming - 17 3.140000
  
*/

 



answered Jun 10, 2024 by avibootz

Related questions

1 answer 121 views
1 answer 107 views
107 views asked May 9, 2022 by avibootz
2 answers 214 views
214 views asked Aug 4, 2017 by avibootz
1 answer 127 views
1 answer 102 views
102 views asked Feb 28, 2022 by avibootz
1 answer 104 views
104 views asked Dec 20, 2021 by avibootz
...