Search code examples
arrayscpointersmemory-address

passing the address of array element NOT working in - C -- the way I did


My swap function and the way I am passing the address of array element to swap is not causing any effect I also tried passing it like swap(&arr[2],&arr[3]) but no luck

void swap(char *a,char *b)
{
    int t=*b;
    b=a;
    a=t;
}

void main()
{
    char *arr=(char[]){'a','b','c','d','e','f'};
    int n=strlen(arr);
    swap((arr+2),(arr+3));
    for(int i=0;i<n-1;i++)
    {
        printf("%c \n",*(arr+i));
    }
}

Solution

  • When you pass things to functions in C, the argument is pushed to the stack (or stored in registers, either way, you only have a local copy of that variable), not a reference to that argument. So when you pass pointers and assign them a different value, that assignment is only valid for the scope of that function. so in

    void swap(char *a,char *b)
    {
        int t=*b;
        b=a;
        a=t;
    }
    

    You are assigning the swap functions local copy of the pointer b to the local copy of a. So when this function returns, the local copies are lost. So you must assign a value at the location the pointer. Also, the next line,

    a=t;
    

    You are assigning a pointer to a value, a big no no in C. So, your swap function should look like this

    void swap(char *a,char *b)
    {
        char t=*b;
        *b=*a;
        *a=t;
    }