简体   繁体   English

从 function 在除 main 之外的其他文件中返回指向字符数组的指针

[英]returning pointer to a character array from a function in a different file other than main

I can't return a pointer to a character array from a different file other than the main function.除了主 function 之外,我无法从其他文件返回指向字符数组的指针。 It always says "segmentation fault".它总是说“分段错误”。 But if I write the function in the same file as main, There is no problem.但是如果我把function和main写在同一个文件里,就没有问题了。

/* this is in mainfunc.c file*/
int main()
{


    char ch[5]={'a','b','c','d','\0'};
    char *res=retchararray(ch);
    printf("%s\n",res);/*I get segmentation fault only when I use this printf*/

}

/* this function is in other file newfile.c */

char *retchararray( char *p){

    char *str;
    str=p;
    unsigned int len=strlen(p);

    *(str+len)='e';
    *(str+len+1)='\0';

    return str;

}

I use netbeans on Mac OS to do C Programming.我在 Mac OS 上使用 netbeans 进行 C 编程。

Can some please tell me what is the problem?有人可以告诉我是什么问题吗? Or Am I doing some mistake here?或者我在这里做错了什么?

The function retchararray overflows your array. function retchararray 溢出您的数组。 You use more memory than you have reserved.您使用的 memory 比您预留的多。 This happens in *(str+len+1) = '\0' and causes the segfault.这发生在*(str+len+1) = '\0'并导致段错误。

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

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