Question

Within an assignment, which I program in C, I need to concatenate the symbol '#' and an integer, for instance 16, to the string "#16". This is not to be printed out, but to be passed on as an argument to another function. By my understanding, I should use the function sprintf. However, I am getting segmentation errors, so I'm obviously not doing it right. I'll give you an example, and you can tell me what I am doing wrong:

void methodA(){
    char* input;
    sprintf(input, "#%d", 16);
    methodB(input);
}

void methodB(int a){
    // Code here

    // Sacrifice the power of a to Darth Sidious
}

EDIT: To those who answered first: char input was a typo, it was supposed to say char* input, I knew that already. Sorry about that.

Was it helpful?

Solution

sprintf takes char*, not char.

int sprintf(char *str, const char *format, ...);

And yes, prefer using snprintf

OTHER TIPS

You're not initializing input so it points to undefined memory. Allocated memory first

void methodA(){
    char input[SIZE];  // or char* input = malloc(SIZE);
    sprintf(input, "#%d", 16);
    methodB(input);
}
void methodA(){
    char input[4];
    sprintf(&input[0], "#%d", 16);
    methodB(&input[0]);
}

void methodB(char *a){
    // Code here

    // Sacrifice the power of a to Darth Sidious
}

Note, I used the '&x[offset]' style to make it clear that we are passing the address of the first element of an array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top