Strings in C

Strings in C

·

3 min read

Table of contents

No heading

No headings in the article.

As you may know, C doesn't have a data type for declaring strings. This may seem odd to you if you know some other programming languages, that all have strings. C has a built-in '%s' operator which can be used to print strings, but how can you store strings in variables? well, I can think of a few solutions :

  1. Array declaration : In order to declare strings, you first need to understand what a string actually is. A string, is an array of characters, meaning that strings are actually chains of individual characters. You just need to declare an array of any size you want and assign it, the string value enclosed in double quotes.
#include <stdio.h>

int main (void) 
{
char str[3] = "Hi!";

printf("%s\n",s);

}

The output would look like - Hi!

Inputting a string is comparatively harder. You need to get memory from a library and use it to ask the user for a string.

#include <stdio.h>
#include <stdlib.h>

int main (void) 
{

    char s[3];
    for(int i = 0; i<3; i++){
    s[i] = malloc(3*(sizeof(char))); //getting memory for 3 chars from the user
    }
    scanf("%s",s);
    printf("%s\n",s);
    free(s);

}
  1. Pointer declaration : In C, there are variables to store the address of certain things, like characters or integers. These pointers can help us store the address of characters, which form, you guessed it, a string. Now, how would you implement this in code? Well, a pointers is declared by '*', and a string stores a double quote value, so you might write this in code as -
#include <stdio.h>

int main (void) 
{
char *s = "Hi!";
printf("%s\n",s);

}

The output would look like - Hi!

String input :

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char *s = malloc(3*(sizeof(char))); // getting as much memory required for 3 chars
    scanf("%s",s); // getting the string
    printf("%s\n",s); // printing the string
    free(s); // freeing the memory
}
  1. Creating a string : In my opinion,this is the easiest and most efficient way to deal with strings. You don't have a string data type? just create one! I know you're probably thinking that it's some advanced code but trust me, its not. To create your own data type, the function typedef is used. You use this (function?) and then the format which it replaces.
#include <stdio.h>

typedef char *string; //string is the name you want to call the datatype

int main(void)
{
string s = "HI!";
printf("%s\n",s);
}

To input a string :

#include <stdio.h>

typedef char *string; //string is the name you want to call the datatype

int main(void)
{
string s;
scanf("%s",s);
printf("%s\n",s);
}

And these are my 3 favorite ways to declare Strings!