I want to create a substring, which I see online everywhere and it makes sense. However, is there any way to, instead of outputting to a regular array of characters, output the substring as a char* array?
This is the idea of my code:
char *str = "ABCDEF";
char *subStr = calloc(3, sizeof(char));
memcpy(subStr, &str[3], 3);
fprintf(log, "Substring: %s", subStr);
I am hoping this will print out DEF. Let me know what you guys think I should do, or if this will work. Thanks!
If you need just to output a substring then you can write
fprintf(log, "Substring: %.*s", 3, str + 3);
Here is a demonstrative program.
#include <stdio.h>
int main(void)
{
char *str = "ABCDEF";
FILE *log = stdout;
fprintf(log, "Substring: %.*s", 3, str + 3);
return 0;
}
The program output is
Substring: DEF
Your code does not create C substring as you allocate only 3 element char array, but you also need the 4th one for the null terminating character.
char *str = "ABCDEF";
char *subStr = calloc(4, sizeof(char));
memcpy(subStr, &str[3], 3);
or less expensive
char *str = "ABCDEF";
char *subStr = malloc(4);
memcpy(subStr, &str[3], 3);
substr[3] = 0;
You should also check if the result of the allocation was successful,
char *str = "ABCDEF";
char *subStr = calloc(4, sizeof(char));
if(subStr) memcpy(subStr, &str[3], 3);
You have to terminate the string by adding terminating null-character.
const char *str = "ABCDEF"; /* use const char* for constant string */
char *subStr = calloc(3 + 1, sizeof(char)); /* allocate one more element */
memcpy(subStr, &str[3], 3);
fprintf(log, "Substring: %s", subStr);
calloc()
will zero-clear the buffer, so no explicit terminating null-character is written here.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.