17

我想从函数返回一个字符数组。然后我想把它打印在main. 我怎样才能让字符数组恢复main正常?

#include<stdio.h>
#include<string.h>
int main()
{
    int i=0,j=2;
    char s[]="String";
    char *test;

    test=substring(i,j,*s);   
    printf("%s",test);
    return 0;
}


char *substring(int i,int j,char *ch)
{
    int m,n,k=0; 
    char *ch1;
    ch1=(char*)malloc((j-i+1)*1);
    n=j-i+1;

    while(k<n)
    {   
        ch1[k]=ch[i];
        i++;k++;
    }   

    return (char *)ch1;
}

请告诉我我做错了什么?

4

3 回答 3

8
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char *substring(int i,int j,char *ch)
{
    int n,k=0;
    char *ch1;
    ch1=(char*)malloc((j-i+1)*1);
    n=j-i+1;

    while(k<n)
    {
        ch1[k]=ch[i];
        i++;k++;
    }

    return (char *)ch1;
}

int main()
{
    int i=0,j=2;
    char s[]="String";
    char *test;

    test=substring(i,j,s);
    printf("%s",test);
    free(test); //free the test 
    return 0;
}

这将在没有任何警告的情况下正常编译

  1. #include stdlib.h
  2. 通过test=substring(i,j,s);
  3. 删除m,因为它未使用
  4. 在 main 之前声明char substring(int i,int j,char *ch)或定义它
于 2013-05-08T15:10:50.930 回答
4

评论中的懒惰笔记。

#include <stdio.h>
// for malloc
#include <stdlib.h>

// you need the prototype
char *substring(int i,int j,char *ch);


int main(void /* std compliance */)
{
  int i=0,j=2;
  char s[]="String";
  char *test;
  // s points to the first char, S
  // *s "is" the first char, S
  test=substring(i,j,s); // so s only is ok
  // if test == NULL, failed, give up
  printf("%s",test);
  free(test); // you should free it
  return 0;
}


char *substring(int i,int j,char *ch)
{
  int k=0;
  // avoid calc same things several time
  int n = j-i+1; 
  char *ch1;
  // you can omit casting - and sizeof(char) := 1
  ch1=malloc(n*sizeof(char));
  // if (!ch1) error...; return NULL;

  // any kind of check missing:
  // are i, j ok? 
  // is n > 0... ch[i] is "inside" the string?...
  while(k<n)
    {   
      ch1[k]=ch[i];
      i++;k++;
    }   

  return ch1;
}
于 2013-05-08T15:04:53.753 回答
4

丹尼尔是对的:http: //ideone.com/kgbo1C#view_edit_box

改变

test=substring(i,j,*s);

test=substring(i,j,s);  

此外,您需要转发声明子字符串:

char *substring(int i,int j,char *ch);

int main // ...
于 2013-05-08T14:53:00.833 回答