首先,我知道在这个实例中使用malloc是一个糟糕的实践;我只是好奇为什么下面的代码不能工作(逻辑上,没有编译或运行时错误)

#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;

}

最佳答案

p[i]应该是p[i-n],您还需要复制空值:

#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;
}

关于c - 字符串不输出任何内容,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23061239/

10-15 17:57
查看更多