C Language Learning 018: strdup copying string array, 018 strdup
In C Language Learning 005: the strings that cannot be modified are stored in the constant area. Assigning a value to the array actually copies the strings in the constant area to the stack memory, if we assign this array to the pointer, we can change the elements in the array, as shown below
1 int main () {2 char s [] = "hello c"; 3 char * temp = s; 4 temp [0] = 'a '; 5 temp [1] = 'B'; 6 printf ("% s \ n", s); 7 return 0; 8}
But now we don't want the pointer to modify the elements in the string array, but we can get the elements in the string, so we need to copy a copy of the elements in the string array, then, the address is given to the pointer, which can be implemented through strdup.
1 int main () {2 char s [] = "hello c"; 3 char * temp = strdup (s); 4 temp [0] = 'a '; 5 temp [1] = 'B'; 6 printf ("% s \ n", s); 7 return 0; 8}