0
Follow
0
View

Find the reason why ABCXDEF is output

x309007873 注册会员
2023-02-27 23:47

  • First defines a two-dimensional character array p containing three string constants "ABC", "DEF", and "XYZ", each with a space of four characters.
  • then defines a pointer array q containing three pointer variables pointing to the three string constants in the array p. Note that the pointer variables in the q array are not initialized, so q[0], q[1], and q[2] initially point to an indeterminate memory location.
  • Then, the code points q[0], q[1], and q[2] to p[0], p[1], and p[2], respectively, so that the pointer variable in the q array now points to each of the three string constants in the p array.
  • The following statement ( (q+1)-1) = p[2] is used to assign the first character of the string constant "XYZ" to the first character of the string constant "DEF". Specifically, q+1 represents the address of the second element in the q array(i.e. q[1]), and (q+1) represents the beginning address of the string constant "DEF" that q[1] points to, so (q+1)-1 represents the address of the first character in the string constant "DEF". Also, p[2] represents the first address of the third element in the p array(i.e., "XYZ"), so p[2] represents the first character of "XYZ". Thus, the effect of ( (q+1)-1) = *p[2] is to assign the first character of "XYZ" to the first character of "DEF", that is, the character 'X' to the variable p[1][0].
  • The last line puts(*p) does what puts(*p) does by calling the standard library function puts() to output the string constant, taking as an argument the beginning address of "ABC", the first string constant in the p array. Therefore, the output of the program is "ABCXDEF". Note that since the string constants "ABC" and "DEF" in the p array are stored next to each other, there are no null characters between "DEF" and "ABC" after assigning "X" to the first character of "DEF", Therefore, there is no space or other separator between "ABC" and "DEF" in the output.