Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

How can you make text in C?

+14 votes
asked Dec 22, 2023 by Jose Marco Eugenio (220 points)
I've seen some examples, but they don't seem to work under this compiler (terms don't exist within the compiler's library etc)

2 Answers

0 votes
answered Jan 6 by banan4ik (200 points)
In C, you can create text (strings) in several ways:

1. **Directly**: You can create a string by initializing it with a string literal. A string literal is a sequence of characters enclosed in double quotes. For example:

char str[] = "Hello, World!";

2. **Using pointers**: You can also create a string by defining a character pointer and assigning it to a string literal. For example:

char *str = "Hello, World!";

3. **Using `malloc()`**: If you want to create a string dynamically (i.e., at runtime), you can use the `malloc()` function to allocate memory for the string. For example:

char *str = malloc(14 * sizeof(char)); // Allocate memory for 14 characters
strcpy(str, "Hello, World!"); // Copy the string literal into the allocated memory

Remember to include the `<string.h>` header file if you're using `strcpy()`.

4. **Using `strdup()`**: If you're using a system that supports it (like GNU C Library), you can use `strdup()` to create a new string that is a duplicate of an existing string. For example:

char *str = strdup("Hello, World!");

Remember to include the `<string.h>` header file if you're using `strdup()`.

Please note that in C, strings are just arrays of characters, and the last character of a string is always the null character (`'\0'`).
0 votes
answered Jan 8 by Peter Minarik (89,230 points)
Can you link the said examples?

What do you mean by text?! (A string; something on the standard output; a graphics UI with text printed on it, as in a label/text box/etc?)

Please, provide more details.
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.