Search code examples
cmacosprintfitoa

C int to char array on Mac OS X


I'm trying to convert an int to a char*. I'm on a Mac OS X so I can't use itoa, since it's non-standard, I'm trying to use sprintf or snprintf but I keep on getting segmentation fault: 11. Here's what I've got:

snprintf(msg, sizeof(char *), "%d", 1);

So I'm hoping for a suggestion, what can I do?


Solution

  • It's likely that msg, which is a char *, doesn't point to memory that it can use. So you first have to dynamically allocate memory that will be used to store the string.

    msg = malloc(12); // 12 is an arbitrary value
    snprintf(msg, 12, "%d", 1); // second parametre is max size of string made by function
    

    Alternatively, you can instead declare a static buffer. That way, you won't have to free any memory.

    char msg[12]; // again, 12 is an arbitrary value
    snprintf(msg, sizeof(msg), "%d", 1);