Skip to main content

Character pointer

Pointer to character:
What is character pointer?
If the base type of a pointer is a character, then the pointer is called character pointer or pointer to character.

How to declare character pointer?
Below is the declaration for character pointer.
          char *<variable_name>;
          char *ptr;

How to initialize character pointer in c?
Below are few examples for character pointer initialization.
     char *ptr = NULL;
     char *ptr = "Hello world";

What is the size of character pointer?
The size of character pointer can be obtained using the sizeof() operator


Program:

  #include <stdio.h>
  int main() {
        char *cptr;
        printf("Sizeof character pointer: %d bytes\n", sizeof(cptr));
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Sizeof character pointer: 4 bytes



How character pointer works?
Basically, a string is an array of characters terminated with null character '\0'.  And it can be accessed using pointer of type char.  Consider the below declarations.
          char str[16] = "Hello World";
          char *cptr;

Here, str is an character array and cptr is a character pointer.  Let us assign the base address of the array str to pointer cptr
          cptr = str;
Now, pointer cptr refers to the first character in the array str.

Below are few other ways to access characters in an array using pointers.
(cptr + i)  <=> &str[i]  // refers to ith element in array str
cptr[i]      <=> str[i]    // character at ith index of array str
*(cptr +i) <=> str[i]    // character at ith index of array str

How to print a string using pointers in c?
Below program explains how to print a string using character pointers.


  #include <stdio.h>
  int main() {
        char *cptr, str[32] = "Hello world";

        /* assigning base address of the array str */
        cptr = str;

        /* printing the output */
        printf("Input string: ");
        while (*cptr != '\0') {
                printf("%c", *cptr++);
        }

        printf("\n");
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Input string: Hello world



How to compare strings using character pointers?
Consider two characters pointers cptr1 and cptr2.  And they point to two different strings.
          char *cptr1 = "Hello world";
          char *cptr2 = "Hello world";
Let us check whether the strings pointed by two given pointers are same or not.


  #include <stdio.h>
  int main() {
        int flag = 0;
        char *cptr1 = "hello world";
        char *cptr2 = "hello world";

        /* checking whether the given 2 strings are same */
        while (*cptr1 == *cptr2) {
                if (!*cptr1 && !*cptr2) {
                        flag = 1;
                        break;
                }
                cptr1++, cptr2++;
        }

        /* printing the result */
        if (flag) {
                printf("Given two strings are same\n");
        } else {
                printf("Given two strings are not same\n");
        }
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Given two strings are same



How to pass character pointer as function argument? How to return character pointer?
Like other data types, character pointer can also be passed as function argument.  Below program explains how to pass character pointer as function argument and how to return character pointer.


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

  /* returns a string "hello world" to the caller */
  char * charPtr(char *src) {
        char *tmp, *dest, *ptr = "world";

        /* dynamic memory allocation */
        dest = (char *)calloc(32, sizeof(char));

        tmp = dest;

        /* copying hello in src to dest pointer */
        while (*src) {
                *dest = *src;
                src++, dest++;
        }

        /* appending space */
        *dest++ = ' ';

        /* copying the string "world" */
        while (*ptr) {
                *dest = *ptr;
                ptr++, dest++;
        }

        /* null termination */
        *dest = '\0';
        dest = tmp;

        /* returning null pointer */
        return (dest);
  }

  int main() {
        char *cptr1, *cptr2 = "Hello";
        /* passing character pointer as argument */
        cptr1 = charPtr(cptr2);
        printf("Ouput: %s\n", cptr1);

        /* release the dynamically allocated block */
        free(cptr1);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Ouput: Hello world


Comments

Popular posts from this blog

restorecrtmode example in c

Header file:     graphics.h Synopsis:        void restorecrtmode();       Description:       restorecrtmode() restores screen mode to text mode. restorecrtmode function in c graphics   #include <graphics.h>   #include <stdlib.h>   #include <stdio.h>   #include <conio.h>   int main(void) {         /* request auto detection */         int gd = DETECT, gmode, err;         int midx, midy;         /* initialize graphics and local variables */         initgraph(&gd, &gmode, "C:/TURBOC3/BGI");         /* read result of initialization */         err = graphresult();         if (err != grOk) {                 /* an error occurred */               ...

How to install JDK and setting environment variables for java

In this tutorial, we are going to see the following. How to install JDK How to run java program without setting java path How to set temporary java path in windows How to set permanent java path in windows How to install JDK? Check whether JDK is installed on your PC.  If it is not installed, please go to the below link and download JDK under Java SE(Java Standard Edition) in oracle website . Install the downloaded JDK in your PC. Once JDK is installed, you can run your java program using any method shown below. Having your java source code under jdk/bin, compile the source code and run the program from same directory Setting temporary path for java, compiling the source code and running the program from any location using command prompt Updating the java path in system or user variable(in system properties), compiling the source code and running the program anywhere using command prompt Let us see how to run java program without setting environmental variables.  Once java is ...

Save image in Microsoft Paint without white background

Here, we are going to see how to save image in mspaint without white background 1. Create your own drawing or painting 2. Crop the needed portion of your drawing or painting or image. Here, I am going to crop the porting inside the red box. Now, we have cropped the portion that needs to be saved as an image. 5. Clear the screen and paste the image which we cropped earlier. 6. Decrease the screen size by 50% 7. Now, adjust your screen to fit to your image size. 8. Save the image to desired file format(jpeg, png, bmp etc) 9. Go to the saved location and open the file.  Below is the output image of mine Hope you liked this article!!  For any suggestions, please comment below.