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

scanf() and printf() functions

Scanf() function: It is used to read input from the keyboard. int scanf(const char *format, ...); For better understanding, lets rewrite the above as follows. scanf("format specifiers", &v1, &v2, &v3); v1, v2 and v3 are the input variables whose value needs to read from the keyboard.  We need to pass address of the variable as argument to store the input values from keyboard. Here, ampersand(&) represents address. &v1 - address of variable v1 Input value for v1 will be stored at address of variable v1 Format specifier can be any of the following %u  - unsigned int %d  - int %x  - hexadecimal %o  - octal %f  - float %lf - double %c  - char %s  - string scanf("%d", &v1); - inputs integer value scanf("%x", &v2); - inputs hexadecimal value scanf("%f", &v3); - inputs float value printf() function: It prints the given data on the output screen. printf("format specifiers", v1, v2,..vn); Here, format specifier ...

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 ...

Multidimensional arrays in C

Multidimensional array is also known as array of arrays.  C allows user to write arrays with one or more dimensions.  An array with more than one dimension is a multi-dimensional array.  Two dimensional array is a simplest form of multidimensional array.  Below is the general form of multidimensional array. data_type  array_name[size1][size2][size3]..[sizeN]; Consider the following example int arr[2][2][2] = {   { {1, 1}, {1, 1} },                                   { {1, 1}, {1, 1} }                               } ;   The above statement shows the declaration and initialization of multidimensional array(3d array).  Total number of elements in an array can be obtained by multiplying the size value in each dimension. int arr[2][2][2]; 2 X 2 X 2 = 8 elements in the array arr And multidim...