Bifalgorithm post · Computer science one · Arrays of Strings

How can you turn part of a string into a character pointer?

How can you turn part of a string into a character pointer? (Computer science one · Arrays of Strings) — "Using the referencing operator, we can turn the 8th c…

Ideas in this flowchart

  • Using the referencing operator to extract part of a character array as a character pointer
  • The expression &name[7] points to the 8th character of name
  • Full example of allocating and copying the middle name
  • name is initialized with the string "Thomas Alan Waits"
  • middleName is allocated space for five characters
  • strncpy copies five characters from &name[7] into middleName
  • The fourth position of middleName is manually set to '\0'
  • The allocation includes space for a null-terminating character
  • In this case, strncpy does not insert the null-terminating character automatically
  • After termination, middleName holds "Alan"
Feed/

How can you turn part of a string into a character pointer?

No cover

Channel

Computer science one

1 page

"Using the referencing operator, we can turn the 8th character into a character pointer, &name[7]. A full example:\n\n1 char name[] = \"Thomas Alan Waits\";\n\n2 char *middleName = (char *) malloc(sizeof(char) * 5);\n\n3 strncpy(middleName, &name[7], 5);\n\n4 middleName[4] = '\\0';\n\n5 //middleName now holds \"Alan\"\n\nIn the call to malloc(), we included space for a null-terminating character. Furthermore, strncpy() does not insert the null-terminating character for us in this case. In line 4 we manually insert it."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.