Monday, January 9, 2023

C: char pointer vs array

In C, the difference between a char pointer and char array becomes clear when you want to do assignment:

  #include<stdio.h>
  #include<string.h> //for strcpy
  int main() {
      char s[][10] = {"aaa", "bbb", "ccc"};
      //char* s[] = {"aaa", "bbb", "ccc"}; //same as above
      char* t1 = s[1];
      char t2[10]; strcpy(t2, s[1]);
      //t2 = s[1];// error: assignment to expression with array type
      printf("s[1] = %s\n", s[1]);
      printf("t1 = %s\n", t1);
      printf("t2 = %s\n", t2);
      return 0;
  }

s[1] is a char pointer. You can assign a char pointer to another char pointer but you cannot assign a char array to char pointer, you have to use strcpy. 

Another interesting difference:

    char a[] = "string1"; 
    char *p1  = a;
    char *p2  = "string2";
    a[0] = 'z';
    printf("a[0] = %c\n", a[0]);
    p1[0] = 'k'; //works fine, changes a[0]
    printf("a[0] = %c\n", a[0]);
    p2[0] = 'm'; //results in segmentation fault
    printf("p2[0] = %c\n", p2[0]);

No comments:

Post a Comment