I would like to input a string with dynamic allocation like in the picture and print the index number 5 to the end of the string. What's the problem here?
In the last printf, we found that word [5], not word [5]. Please explain why.
dynamic
If you approach the char * type variable as an index ([]), the char value for that position is returned, which is a character (char *), not a string (char *). The %s format does not print properly because it receives a string.
The variable word
points to the first location of the assigned memory address, so if you want to output from the fifth character, you can use the pointer by adjusting the location, such as word + 5
.
&
is an operator that gets the address of the variable, and using &
for word[5]
returns the address of the location, which eventually means word + 5
.
When you output something like %d or %f from the printf function, you can write down the value directly or put in the variable.
Unlike others, %s must write the beginning of the string address. As you said above, word[5] is the value of the sixth character, and & word[5] is the address where the sixth character is stored. If you insert & word [5] in the %s, the string will be printed from the sixth column until you meet the null character.
916 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
613 GDB gets version error when attempting to debug with the Presense SDK (IDE)
573 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
© 2024 OneMinuteCode. All rights reserved.