Return function of the next ASCII character in C

Asked

Viewed 169 times

3

Do a function: strShift() that receives a string with alphabet letters and returns a new string with letters replaced by their successors in the ASCII table. For example, "Ana" returns "Bob" and "Zaza" returns "{b[B".

The function must return NULL if no memory is available.

I did:

char* strShift(char *s) {
    int i;
    int tam = strlen(s);
    char* nova = (char*)malloc((tam + 1) * sizeof(char));
    if (nova == NULL)
        return NULL;
    for (i = 0; i < tam; i++) {
        nova = *(s + i + 1) ;
    }
    nova = '\0';
    return nova;
}

I can’t figure out what else to do where I’m going wrong?

The exit gives me a lot of exclamation points.

1 answer

3


There are several problems in the code. I don’t like the idea of allocating memory just for this, it could change directly in the already existing object. But if the exercise This we will do. Remembering that if it was more than an exercise without a free() would leak memory.

I took the irrelevant parts of the code (probably learning from old material.

Access to content is confusing and more complicated than it should be, just access it as if it were a array, so avoids problems, ended up mixing address with content and did everything one thing only, separating the concepts more clearly becomes easier to hit. Do the simple first, use the easy syntax.

At some points you should access the elements of string and did not put any index for it so automatically the index is 0, and then when you put the terminator in the wrong place already melou the text.

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

char *strShift(char *s) {
    int tam = strlen(s);
    char *nova = malloc(tam + 1);
    if (nova == NULL) return NULL;
    for (int i = 0; i < tam; i++) nova[i] = s[i] + 1;
    nova[tam] = '\0';
    return nova;
}

int main(void) {
    printf("%s", strShift("anaz"));
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Friend, pardon. I forgot to mention some other features that the exercise asked for. As for example the use of pointer arithmetic, my fault. However, I have already solved here with what you answered. Thank you very much and big hug!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.