ASCII next character return function in C

Question:

Make a function: strShift() which takes a string with alphabet letters and returns a new string with the 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 there is no memory 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 understand what to do anymore, where am I going wrong?

The output gives me a bunch of exclamation points.

Answer:

There are several problems in the code. I don't like the idea of ​​allocating memory just for that, it could change directly on the existing object. But if we do this exercise, let's do it. Remembering that if it were more than one exercise without a free() leak memory.

I removed the extraneous parts of the code (you are probably learning from old material.

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

At some points it should access the elements of the string and it didn't put any index for it, so automatically the index is 0, and then when you put the terminator in the wrong place, the text has already melted.

#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"));
}

See working on ideone . And on repl.it. Also posted on GitHub for future reference .

Scroll to Top