Pointers in C – String Implementation

In the previous blog post, I wrote about the relationship between pointer and array. I suggest you reading that post before starting here because this is an extension of that post. In this post, I would like to show you the implementation of string using pointers in C programming language.

Pointers in C, String Implementation. String is an array of characters and hence pointers can be used.
String as an array of characters

An Example

In C programming language, there is not a native way to input string directly. Hence, one must use the array of characters to implement string in C. Therefore, you must determine a maximum size that you are going to use in your application, otherwise there will be some errors. Hence, in this way, we can use pointers in C for the implementation of string.

#include <stdio.h>
#define MAX_NAME_SIZE 50

int main()
{
    // A string is an array of characters hence, its size must be defined
    char name[MAX_NAME_SIZE];
    
    
    // Size of the array
    size_t size = sizeof(name) / sizeof(name[0]);
    
    printf("Enter a name: ");
    scanf("%s", name);      // Base address of the string
    // scanf("%s", &name);     // Equivalent 
    // scanf("%s", &name[0]);   // Equivalent
    
    printf("%s", name);

    return 0;
}

In the above code, you can see that name is an array of character. Therefore, we have to assign a size for the array. Also, we know that, scanf takes the memory address, hence we provide the base address of the array. i.e. either &name or name or &name[0]. For the simplicity, we use name.

There are many things that we have to consider while including string in our program. For example, in Java, string data types are immutable. That is, when you cannot reassign it directly. In C, you can do this by make it const char *. In this way, you don’t have to worry about modifying the string. Furthermore, there is a library <string.h> which you can use for the manipulation of string in C. Most of the functions in this library use const type as arguments.

I hope this blog post have been helpful to you for understanding the concept. You can leave a comment below for the queries. If you like to visit my github profile, follow this link: https://github.com/mrkrishnaupadhyay . For more articles, please surf through my website, and leave likes and comments. And also, please don’t forget to share.

I am a Computer Engineer from Pulchowk Campus, IOE. I love programming, and music. Python, Java, Php, Javascript, Django, Laravel, Spring, express.js, etc. are my specialities.

Leave a Reply

%d bloggers like this: