How to get the first N characters of a string in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void) {
    char s[] = "java c c++ c# php python";

    char *first_N_chars = malloc(strlen(s) + 1);
    if (first_N_chars == NULL) {
        puts("malloc error");
        exit(1);
    }
    
    int N = 12;
    strncpy(first_N_chars, s, N); 
    first_N_chars[N] = '\0';
    
    printf("%s", first_N_chars);
    
    free(first_N_chars);
}




/*
run:

java c c++ c

*/

 



answered Feb 23, 2021 by avibootz
edited Feb 23, 2021 by avibootz

Related questions

1 answer 127 views
1 answer 108 views
2 answers 134 views
1 answer 121 views
1 answer 166 views
1 answer 164 views
...