Whoknowsdude
Whoknowsdude

Reputation: 1

How can I update a string in C

So I have an array of strings. Im using this to send messages to the client.

char *server_msg[] = {"Welcome to the game!", "The sum is: ", "GO", "END", "ERROR"};

I want to be able to update [1] with the score so it would look like could look something like

{"The sum is: %d", player_sum}

I am sending messages to the clients like this eg to welcome the player to the game.

send(client_sockfd[i], server_msg[0], sizeof(server_msg), 0);

How could I append an int to that string is it possible? Or any tips on where to look.

Thank you.

Upvotes: 0

Views: 193

Answers (1)

Jeremy Friesner
Jeremy Friesner

Reputation: 73091

How could I append an int to that string is it possible?

Modifying a string-literal isn't possible, since they are typically located in a read-only portion of the executable.

You could dynamically generate the string you want to send, though:

char buf[128];
int n = snprintf(buf, sizeof(buf), "The sum is: %i", sum);
send(client_sockfd[i], buf, n + 1, 0);  // +1 for the NUL terminator byte

Upvotes: 3

Related Questions