How the " char *atr "-works,what is it working principle and and explain the code ,why this makes a answer " fg " ?. | SoloLearn: Learn to code for FREE!

0

How the " char *atr "-works,what is it working principle and and explain the code ,why this makes a answer " fg " ?.

char *atr; char srr[]={"abcdefg"}; tr=srr; atr+=5; cout<<atr<<\n;

8/14/2020 5:56:42 PM

ILLUMINATIE

2 Answers

New Answer

+4

You will understand these things when you understand the relationship between pointers and arrays. What arrays really are. atr is a pointer of type char* srr is an array. An array is a contiguous blocks of memory. An array can be assigned to a pointer, when it is done, it decays to the address of the first element of the array. We can still access all elements of an array because the memory of the array is allocated as one contiguous block, which implies if we know one address in that block we can find the address of other cells using pointer arithmatic and the values stored in those cells. atr = srr; (note you have written tr) when you do that, atr is assigned the address of 1st element of the array srr so atr = srr = &srr[0]; // indexing starts from 0 and name of the array is a pointer in itself and points to first element of the array atr += 5; the pointer is incremented by 5 elements so atr += 5 = atr = atr + 5 * sizeof(char) remember after atr = srr, so adding 5 makes atr points to index 5 in the array. At index 5 you have character 'f' now when you do cout << atr; the compiler displays the string starting from that point till it encounters '\0' (null terminator) so you get "fg" as your output.

+1

char *atr; // charecter pointer char str[] = "abcdefg" ; //charecter array assigned with sequence of letters.. atr = str ; // now both point to the same charecter sequence.. atr = atr + 5; now atr pointer is advanced to 5 charecter locations further in sequence so now it points to "fg" "abcdefg" 012345 cout <<atr; output fg.