1

I want to reverse a char array using pointers, but all I get when I printf the pointer is null. I don't know what I'm doing wrong or how to fix it. So how can I reverse the string in a similar way?

#include <stdio.h>

void reverse(char *cstr);

int main()
{
    char a[100];
    char *p = a;
    printf("geef een string ");     // ask user to write a word
    scanf("%s", &a);

    reverse(p);

    printf("%s", *p);
}


void reverse(char *p)
{
    int i = 0;
    char temp;
    int lengte;

    for(i = 0; *(p+i) != '\0'; i++)
    {
        lengte++;                        // length of char array without the '\0'
    }

    for(i = 0; i < lengte; i++)
    {
        temp = p[i];               // something goes wrong here but I don't know  what
        p[i] = p[lengte-i];
        p[lengte-i] = tem;
    }
}

Something goes wrong at the

p[i] = p[lengte-i];
p[lengte-i] = tem;

part. What do I need to change it to?

2
  • 2
    Something? Almost everything. UB with scanf() and printf() (mismatching types: you have either too much or too few levels of pointers); then you reverse the string twice. I suggest you read a good beginner C book before trying to proceed any further. Commented Nov 6, 2013 at 22:09
  • 1
    Compilable code (albeit 2 warnings, 1 error that is clerical). Has a question. Goal stated. Formatting not too bad. Accepted an answer. Yeah, could be better but IMHO, above par for an OP's 1st post. Commented Nov 6, 2013 at 22:36

1 Answer 1

1

Two adjustments:

replace

printf("%s", *p);

with

printf("%s", p);

because printf is expecting a pointer, not a dereferenced pointer, and

for(i = 0; i < lengte; i++)

with

for(i = 0; i < lengte--; i++)

because your counting of the length in the loop before that one ends up with one char too many. Hence the \0 is placed at the beginning of the string.

$ gcc test.c && ./a.out
geef een string 1234
4231$
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.