What is Difference between char pointer and char array?

Difference between char pointer and char array

Pointers and arrays are fundamentally different: an array is a sequence of contiguous objects, and a pointer is an object that holds the address of another object.

  • Suppose you have string “wiki”
    char *ptr=”wiki”;
    char array[]=”wiki”;
    Now if you want to change a character in this string, suppose you want to change ‘k’  with ‘p’
    ptr[2]=’p’ is not valid while array[2]=’p’ is valid. For example the below program would compile successfully but at run time it will give segmentation fault at line 7 ( ptr[2]=’p’).
#include<stdio.h>

int main ()
{
  char *ptr = "Wiki";
  char array[] = "wiki";
  ptr[2] = 'p';
  array[2] = 'p';
  return 0;
}
  • From c++ perspective if we declare char *ptr = “wiki” then new is valid i.e we can point ptr to some other string. in case of char array[] , new operator is not valid something like char array[] =new ..
  • Size of array[] = “wiki” will be 5 (length of the string, plus one for the null terminator) while size of ptr would be size of pointer.
#include<stdio.h>

int main ()
{
  char *ptr = "Wiki";
  char array[] = "wiki";
  printf("size of array %ld\n",sizeof(array));
  printf("size of ptr %ld\n",sizeof(ptr));
  return 0;
}

Output of above program on 64 bit Linux.

size of array 5
size of ptr 8
  • An expression of array type “decays” into a pointer to the first element of that array.
#include<stdio.h>

int main ()
{
  char arr[] = "hello";
  char *s = arr; 
  // or
  //char *s = &arr[0];
  printf("%s\n",s);
  return 0;
}

Note: Submit your article at myconcept@wikistack.com



Related Contents to follow