sykrish
sykrish

Reputation: 23

Reverse char array with pointer in C

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?

Upvotes: 1

Views: 10086

Answers (1)

damienfrancois
damienfrancois

Reputation: 59090

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$

Upvotes: 1

Related Questions