array return type

后端 未结 5 737
有刺的猬
有刺的猬 2021-01-29 15:25
#include
#include
#define MAX 30

void push(char );


char stack[MAX];
int tos=0;

int main(){
    char str[]=\"Arijit Saha\";
    char *f         


        
相关标签:
5条回答
  • 2021-01-29 16:05

    reverse is a local array. It is destroyed, when the function exits, but you return a pointer to its contents. Ideally, you should return the array by having a parameter that the function will load data into, i.e.

    void MyFuncReturnsArray(int* myArr, int n)
    {
       for(int i = 0; i < n; ++i)
          myArr[i] = i;
    }
    

    Instead of

    int* MyFuncReturnsArray()
    {
         int myArr[10];
         for(int i = 0; i < 10; ++i)
            myArr[i] = i;
         return myArr
    
    }
    
    0 讨论(0)
  • 2021-01-29 16:06

    c:14: error: previous implicit declaration of 'rev' was here

    Your error is because you didn't generate a prototype for rev() before you used it in your main(). Either move your function above main or add a prototype.

    c28: warning: function returns address of local variable

    Your warning is because you are trying to return the address of a local variable, you can't do that. Local variables are out of scope when you leave the function, so you need to do something else (such as use a dynamic array via adding malloc()/free() calls)

    0 讨论(0)
  • 2021-01-29 16:07

    In this code:

    char* rev(char s[]) {
        char reverse[strlen(s)];
        ...
        return reverse;
    }
    

    reverse is an temporary array with automatic storage duration that is being deallocated once the execution leaves the scope of this function. You return a pointer that becomes a dangling pointer.
    Trying access the memory that this pointer points to produces undefined behavior.

    Apart from the fact that you should allocate it dynamically by using malloc, note that strlen returns the length of the string, you will also need the space for the terminating character ('\0'). You should create reverse like this:

    char* reverse = malloc(strlen(s) + 1);
    

    and don't forget to assign '\0' to the last character of reverse. Also don't forget that the caller of this function becomes responsible for deallocating the memory that has been allocated by malloc, i.e. the caller should call free on the returned pointer.

    0 讨论(0)
  • 2021-01-29 16:14

    A variable which has automatic storage duration doesn't exist anymore in the calling function. Accessing to it leads to an undefined behavior (anything can happen). Here you are returning reverse from rev, which is a local variable.

    Rather allocate the memory dynamically:

    int *reverse = malloc(strlen(s)); /* + 1 for '\0' character ? */
    
    0 讨论(0)
  • 2021-01-29 16:22

    char reverse[strlen(s)]; is on the stack. After the function complete it is now invalid, but you are returning its address.

    0 讨论(0)
提交回复
热议问题