字符串不是从返回值函数用C抓获 [英] String is not captured from return value in function in C

查看:117
本文介绍了字符串不是从返回值函数用C抓获的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有是应该合并两个字符串,并返回所得到更长的字符串的函数。该字符串出现在函数成功合并,但返回时,信息会丢失。在函数'输出'包含合并串,并把这个值应该被返回。

I have a function that's supposed to merge 2 strings and return the resultant longer string. The string appears to be successfully merged in the function, but when returned the information is lost. 'output' in function contains the merged string, and this value is supposed to be returned.

的mergedString不主打印,但在功能上打印。为什么?如何使它工作?

The mergedString does not print in main, but prints in the function. Why? How to make it work?

main () {
char  *mergedString = mergeStrings( frags[maxOverlapArrPos1], frags[maxOverlapArrPos2], maxCharOverlap);
   printf ("mergedStringInMain is %s\n", mergedString);
}

char * mergeStrings(char * string1, char * string2, int overlapCharSize){
  int overlapStartPosition = strlen(string1) - overlapCharSize;
  char output[] = "";

  if (strlen(string2)>overlapCharSize){
     strncat(output, string1, overlapStartPosition);
     strncat(output , string2, strlen(string2));
  } 
  printf ("mergedStringInFunction is %s\n", output);
  return output;

}

输出是:

mergedString是ABCDEFG

mergedString is abcdefg

mergedString是什么?

mergedString is ?

推荐答案

您的两个 未定义行为在code:第一个是,你使用数组的一个字符长的和写多个字符进去。第二个是你的指针返回到的局部变量

You have two instances of undefined behavior in your code: The first is that you use an array one character long and writes more than one character into it. The second is that you return a pointer to a local variable.

这篇关于字符串不是从返回值函数用C抓获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆