Sergiu
Sergiu

Reputation: 61

Fix the check '\0' to take a length for the string

In this code I use a for-loop that still checks for '\0' endings. I need to fix it so the function always takes a length for the string to work with inside the function.

If you can give me some explanation how to use length.

#include <stdio.h>
#include <ctype.h>
#include "dbg.h"

int print_a_message(const char *msg)
{
    printf("A STRING: %s\n", msg);

    return 0;
}

int uppercase(const char *msg)
{
    int i = 0;

    // BUG: \0 termination problems
    for(i = 0; msg[i] != '\0'; i++) {
        printf("%c", toupper(msg[i]));
    }

    printf("\n");

    return 0;
}

int lowercase(const char *msg)
{
    int i = 0;

    // BUG: \0 termination problems
    for(i = 0; msg[i] != '\0'; i++) {
        printf("%c", tolower(msg[i]));
    }

    printf("\n");

    return 0;
}

int fail_on_purpose(const char *msg)
{
    return 1;
}

Upvotes: 0

Views: 80

Answers (1)

chux
chux

Reputation: 154305

As @Jonathan Leffler suggests: change the for() loop to terminate based on length rather than finding the null character.

#include <stddef.h>

int uppercase(const char *msg, size_t len)
{
    size_t i = 0;
    for(i = 0; i < len; i++) {
        printf("%c", toupper(msg[i]));
    }
    printf("\n");
    return 0;
}

OTOH, if you need to terminate on length and the null character:

int uppercase(const char *msg, size_t len)
{
    size_t i = 0;
    for(i = 0; msg[i] && i < len; i++) {
        printf("%c", toupper(msg[i]));
    }
    printf("\n");
    return 0;
}

Upvotes: 2

Related Questions