Help. reverse a string with a twist in it...

The purpose of this self-made code is to reverse a string. When i enter ABCD it outputs DCBA.

The code is heavily twisted on purpose. I am playing with it to see what happens but it has some pieces i fail to understand why they work the way they work! It is a mix of c and c++.

1)inside my function inverse(): the statement char *s1[18]; the code in my win32 pc works!! BUT, if i change this to any number less than 10 it crashes, eg *s1[1]. WHY? I do not get it,For me it makes perfect sense this: char s1[0][1] is the same as char *s1[1]; :-(

2) printf("%s", s1); according to what i remember(hopefully) i was expecting to retrieve the one and only element of array *s1 this way but no it crashes in my PC.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
  
#include <iostream>
#include <stdlib.h>
#include <cstdio>


using namespace std;

void inverse (char *s1);

int main(void)

{
    inverse("ABCD"); //feed direclty the string itself into the function.
    return 0;
}

void inverse (char *s)
{
    char *temp, *s1[18]; // <------ *s1[1] fails :(
    temp=s;
    int i=0,j=0;
    while(*s!='\0')
        s++;
    s--;
    while(s>= temp)
    {
        *(*(s1+0)+i) = *(s--);  //copy contents.Copy what pointer s is pointing
                               //to to the 1D array of pointers *s1 character
                              // by character.
        i++;

    }
    cout << *s1 << endl;
    printf("%s", s1);
    return ;
}

Last edited on
The s1[0] (or *(s1+0) or *s1 like you write it) is a pointer.

A pointer holds an address. You never set the value of that pointer. We have no idea what address it holds.

Then you dereference the pointer s1[0][i]. Offset i from whichever undefined location *s1 happens to point to. Writing to a random memory address on line 28 is bad, yes?
Topic archived. No new replies allowed.