c - String prints nothing -


first, know use of malloc in instance poor practice; curious why following code doesn't work (logically, there no compile or runtime errors)

#include <stdio.h> #include <stdlib.h> #include <string.h>   //function remove n number of characters replicated string char* remove_beginning(int n, char a[], int size) {  int i; char *p=malloc(size-(1+n)); for(i = n ;i < size-1; i++)    {      p[i] = a[i];      }  return p;  }    int main(){   char *str = "123456789"; char *second = remove_beginning(5, str, strlen(str));  printf("%s\n", second); return 0;  } 

p[i] should p[i-n] , need copy null also:

#include <stdio.h> #include <stdlib.h> #include <string.h>   //function remove n number of characters replicated string char* remove_beginning(int n, char a[], int size) {   int i;   char *p=malloc(size-(n-1));   for(i = n ;i <= size; i++) {      p[i-n] = a[i];     }    return p; }   int main(){   char *str = "123456789";   char *second = remove_beginning(5, str, strlen(str));    printf("%s\n", second);   return 0; } 

Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -