KAKAK
KAKAK

Reputation: 899

changing values in memory is not working pointers

#include <stdio.h>
#include <string.h>
void reverse(char * str[]) {
    int i;
    int reverse = sizeof(str);

    for(i=0;i<=sizeof(str);i++){
        *str[i]=*str[reverse];
        reverse--;
    }
}

main() {
        char *word;

        printf("Enter a word please=>");
        scanf("%s",word);

        reverse(word);      
        printf("%s",word);
}

I am trying to get a string input and pass it to reverse() function to reverse the word entered i.e ("abcd" -> "dcba"), however i am having some difficulty using pointers.

I am not able to change the values held by the char *word in the memory.

Upvotes: 0

Views: 101

Answers (1)

simonc
simonc

Reputation: 42175

You haven't allocated any storage for word. Change

char *word;
scanf("%s",word);

to

char word[20];
scanf("%19s",word);

There are also a number of issues with reverse

  • Its signature accepts an array of strings rather than a single string (an array of chars).
  • You need to use strlen to calculate the length of a string. sizeof tells you the size of a char** on your platform.
  • You reverse the string twice so will currently reverse it then reinstate the original order.
  • Your reverse algorithm would include reversing the nul terminator. This wouldn't normally be considered part of a string and needs to stay at the end of the array to mark the end of the string.

The following (untested) function should be closer to what you want

void reverse(char* str) {
    int i;
    int len = strlen(str);
    for (int i=0; i<len/2; i++) {
        char tmp = str[i];
        str[i] = str[len-i-1];
        str[len-i-1] = tmp;
    }
}

Upvotes: 3

Related Questions