0

I have recently started using C and am having trouble understanding the use of "&" and "*" and where to put them in my code. The current assignment I have requires me to take two inputs, the character in a string that a user would like to swap and the new character to replace it with. I am not allowed to use the String library. Here is my current code but for some reason, the output is never able to access "replacementchar[0]" and I have no clue why. Any help would be appreciated. Thank you!

if(response[0] == yes[0]){
        char replacechar[1];
        printf("What character do you want to replace: ");
        scanf("%s", replacechar);

        char newchar[1];
        printf("What is the replacement character: ");
        scanf("%s", newchar);

        printf("you want to replace %c with %c \n", replacechar[0], newchar[0]);
        for(int i = len-1; i > -1; --i){
            if(word[i] == replacechar[0] && word[i] != '\0'){
                printf("found one\n");
                word[i] = newchar[0];
            }
        }
    }
  • @user3121023 Or somewhat more sanely, `%c` or `getchar()`. – EOF Feb 01 '20 at 19:07
  • Consider (use) `scanf(" %c", replacechar)` — read a single character skipping leading white space (such as the newline leftover from reading `response[0]`). – Jonathan Leffler Feb 01 '20 at 19:25

2 Answers2

1

In C, * and & are pointer operators. * is used to create pointers variables and dereference them. & is used to get the memory address of something.

The following code (1) creates an int a, (2) creates an int pointer p using * and (3) sets the value of pointer p to the memory address of a using &.

int a;
int *p;
p = &a;

printf("%d", p);
printf("%d", *p);

The first print will return the value of p, which is the memory address of a. In the second print we dereference p, which gives us the data stored at that memory address--the value of int a.

There are other ways to use pointers. When you create an array...

int arr[10];

...you are implicitly creating a pointer ("arr") to the first element in your array. You can access elements if the array in several ways.

arr[5]
*(arr + 5)

Both get the 5th element of the array by looking at arr (the memory address of the first element) and adding 5, which gives us the memory address of the 5th element, then dereferencing that with * to get the value of the 5th element.

...

Your code is wrong not because of a misuse of & and *, but because of the behavior of scanf (which you shouldn't really use). Scanf writes to a buffer, which you then have to copy in order to save the value. Also, considering you're only scanning a single char, there's no need to use a char array. Check out this solution:

char buf, replacechar, newchar;
printf("What character do you want to replace: ");
scanf("%c", &buf);
replacechar = buf;

printf("What is the replacement character: ");
scanf("%s", &buf);
newchar = buf;

printf("You want to replace %c with %c\n", replacechar,
newchar);
for (int i = len-1; i > -1; --i) {
    if (word[i] == replacechar && word[i] != '\0') {
    printf("Found one!\n");
    word[i] = newchar;
    }
}
Tommy
  • 26
  • 3
  • 2
    No need for the variable "buf". Just use `scanf("%c", &replacechar);` and `scanf("%c", &newchar);` – FredK Feb 01 '20 at 21:09
1

Another approach besides getchar or scanf using either %s or %c is to use fgets. Here fgets will read up to two characters from stdin. If choice[1] is a newline, only one other character was entered. Otherwise, clear stdin and prompt to try again.
The replacement function advances a pointer text through each character of the string until the character pointed to *text is the terminating zero.

#include <stdio.h>
#include <stdlib.h>

char fgetschar ( void) {
    char choice[3] = "";

    do {
        if ( fgets ( choice, sizeof choice, stdin)) {//read two characters
            if ( '\n' == choice[0]) {//only newline
                printf ( "\nenter a character\n\ttry again\n");
                continue;
            }
            if ( '\n' != choice[1]) {//did not find expected newline
                while ( fgets ( choice, sizeof choice, stdin)) {
                    if ( '\n' == choice[0] || '\n' == choice[1]) {
                        break;
                    }
                }
                choice[1] = 0;//to make the loop repeat
                printf ( "\nenter one character only\n\ttry again\n");
            }
        }
        else {
            fprintf ( stderr, "fgets EOF\n");
            exit ( EXIT_FAILURE);
        }
    } while ( choice[1] != '\n');

    return choice[0];
}

int replacement ( char *text, char find, char sub) {
    int count = 0;

    while ( text && *text) {//not NULL and not terminating zero
        if ( *text == find) {
            *text = sub;
            ++count;
        }
        ++text;//advance to next character
    }

    return count;
}

int main ( void) {
    char replacechar = 0;
    char newchar = 0;
    char word[] = "a b c d e f g h i j k l m n o p q r s t u v w x y z";

    int size = 21;
    int item = rand ( ) % ( size - (int)( size * 0.6));
    printf ( "item %d\n", item);

    printf ( "What character do you want to replace: ");
    fflush ( stdout);
    replacechar = fgetschar ( );
    printf ( "replace character: %c\n\n", replacechar);

    printf("What is the replacement character: ");
    fflush ( stdout);
    newchar = fgetschar ( );
    printf ( "replacement character: %c\n\n", newchar);

    int found = replacement ( word, replacechar, newchar);

    printf ( "found %d instances of %c\n", found, replacechar);

    printf ( "%s\n", word);

    return 0;
}
user3121023
  • 8,181
  • 5
  • 18
  • 16