-1

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)

  • There is a minor mistake in first loop brackets. Also, calling function name is wrong. – nogabemist May 18 '22 at 10:04
  • `reverseString2(&name);` is invalid C and will not compile. If your compiler let this code through without warnings, it is broken and you need to get a better one. – Lundin May 18 '22 at 10:05

2 Answers2

0

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).

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

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

Barstok
  • 49
  • 6