简体   繁体   English

返回字符数组的函数类型冲突

[英]conflicting types for function returning a char array

Here's my code:这是我的代码:

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

char input_buffer[1000];


void get_substring(){


    int i;
    int length;

    printf("Please enter a string:\n");
    scanf("%[^\n]s", input_buffer);



    printf("Index of first character of substring:\n");
    scanf("%d", &i);

    printf("Length of substring:\n");
    scanf("%d", &length);

    printf("Substring is  %.*s ", length, input_buffer + i);

}


int main(void) {
    // your code goes here

    //get_substring(0,4);
    get_substring();

    return 0;
}

That's my current code, I want to return a pointer of the input, instead of just displaying the substring.这是我当前的代码,我想返回输入的指针,而不仅仅是显示子字符串。 Sorry for the confusion everyone.抱歉给大家带来困惑。

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

char* getSubstring(char* str,size_t start, size_t length)
{
  // determine that we are not out of bounds
  if(start + length > strlen(str))
    return NULL;

 // reserve enough space for the substring
 char *subString = malloc(sizeof(char) * length);
 // copy data from source string to the destination by incremting the 
 // position as much as start is giving us
 strncpy(subString, str + start, length);
 // return the string
 return subString;
}

int main(int argc, char* argv[])
{
  char *str = "Hallo Welt!";
  char *subStr = getSubstring(str,0,20);
  if(subStr != NULL)
  {
    printf("%s\n",subStr);
    free(subStr);
  }

}

This solution should give you a hint how you would start with such a problem.这个解决方案应该给你一个提示,你将如何开始处理这样的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM