Stumbler
Stumbler

Reputation: 2146

String prints nothing

First, I know the use of malloc in this instance is poor practice; I am just curious as to why the following code doesn't work (logically, there are no compile or runtime errors)

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


//function to remove n number of characters from 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;

}

Upvotes: 0

Views: 142

Answers (3)

haccks
haccks

Reputation: 106012

You need to change the loop body and malloc in your function

char *p=malloc(size-(n-1));
for(i = 0 ;i <= size - n; i++)
{
    p[i] = a[i+n];
}

Upvotes: 1

dj bazzie wazzie
dj bazzie wazzie

Reputation: 3542

When removing beginning of a string can also be done with strncpy :

char tmp1[20] = "123456789";
char tmp2[20];
strncpy(tmp2, tmp1 + 5, 4);

I know it doesn't directly answer your question but I post it to show a "better" way of removing beginning of a string. strncpy can be used to copy a complete string, a beginning or end of a string.

Upvotes: 1

imran
imran

Reputation: 1560

p[i] should be p[i-n] and you need to copy the null also:

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


//function to remove n number of characters from 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;
}

Upvotes: 2

Related Questions