Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use pointer math instead of array indexing

Tags:

arrays

c

pointers

I'm trying to solve a problem found on my C programming book.

#include <stdio.h>
char *f (char s[], char t[], char out[]);
int main(void)
{
    char s[] = "ISBN-978-8884981431";
    char t[] = "ISBN-978-8863720181";
    char out[10];
    printf ("%s\n", f(s,t,out));
    return 0;
}
char *f (char s[], char t[], char out[]) {
    int i;
    for (i=0; s[i] == t[i]; i++)
    out[i] = s[i];
out[i] = '\0';
return &out[0];
}

As you can see from the code, this code uses as return value &out[0]: does this means that the complete array is used as return value?

char *f (char s[], char t[], char out[]);
int main(void)
{
    char s[] = "ISBN-978-8884981431";
    char t[] = "ISBN-978-8863720181";
    char out[10];
    printf ("%s\n", f(s,t,out));
    return 0;
}
char *f (char s[], char t[], char out[]) {
    for (; *(s+=1) == *(t+=1);)
            *(out+=1) = *s;
    *(out+1) = '\0';
    return out;
}

This is my proposed solution, but while the proposed code returns "ISBN-978-88", mine only returns "8". The array is smaller than the lenght of the string, how the proposed code can work without any kind of overflow? Thanks for your responses.

like image 774
PeppeLaKappa Avatar asked Mar 01 '26 21:03

PeppeLaKappa


1 Answers

Your code is too aggressive on side effects: the += 1 operation (which is more commonly denoted simply as ++) should be applied after the copy to the output has been made, not after the comparison.

In addition, you need to save the value of the out buffer before incrementing the pointer, so that you could return a pointer to the beginning of the copied string.

char *orig = out;
for ( ; *s == *t ; s++, t++)
    *out++ = *s;
*out = '\0';
return orig;

Demo on ideone.

like image 53
Sergey Kalinichenko Avatar answered Mar 03 '26 11:03

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!