Output method of dynamic assignment string

Asked 2 years ago, Updated 2 years ago, 59 views

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

2022-09-20 21:43

2 Answers

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.


2022-09-20 21:43

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.


2022-09-20 21:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.