'How to change dynamic array in function using C? [duplicate]

I want to create void function that will change existing dynamic (or static) array. How this can be implemented in C and C++? How to properly pass arguments to such functions? For example i want to reverse char array

//function that reverse the string
void reverseString(char* str)
{
    char t;
    int i, j;
    for (j = 0; str[j] != '\0'; j++)
    {
    }
    j -= 1;
    for (int i = 0; i < j; i++, j--)
    {
        t = str[i];
        str[i] = str[j];
        str[j] = t;
    }
}

int main()
{
    char* name = "Ani?321";
    reverseString2(&name);
    printf("%s", name);
}

running this code: Exception thrown at 0x796028BC (ucrtbased.dll) in Strings.exe: 0xC0000005: Access violation reading location 0x00E87B51.

When i changing function parameter from char* to char** -> Run-Time Check Failure #2 - Stack around the variable 'str' was corrupted. (pointing to the closing curly bracket of the main function)



Solution 1:[1]

Well, you have declared a string literal which you can't modify. Declare it like this instead char name[] = "Ani?321";

Solution 2:[2]

You have two major problems:

  1. Your pointer name is pointing to a literal string. Such strings can't be modified, and any attempt to do so leads to undefined behavior. You solve this issue by using an array instead:

    char name[] = "Ani?321";
    
  2. The second problem is that you pass a pointer to the pointer to your function. The type of &name (in your current code) is char **, which is not the correct type and definitely not the correct pointer. You should pass plain name as argument (which will also work when you solve the first problem).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Barstok
Solution 2