Am I missing a pointer point?

OK, sorry for the bad pun: P

I coded the old trick HAL => IBMin C. I just read the first few pages in K & R and I thought it would be a good first game with them.

char evil[] = "HAL";
char *ptr = evil;   
for (int i = 0; i < strlen(evil); ++i, ++ptr) {             
    (*ptr)++;           
}   
printf("%s\n", evil); // IBM

My problem is that I have two variables increasing, iand ptr, and something tells me that one of them is redundant (maybe I still don't think enough C).

The only reason I use iis to determine if we read the end of the line. Is there a way to check the pointer to see if it has arrived at the end of the line?

Update

Sorry for any confusion on the valid question. If I missed what I basically had in mind, why use a pointer when I need an incremental index to check the length. I could just use this index to index the right char from an array.

+3
source share
8 answers

Could you write

for (char *ptr = evil; *ptr != '\0' ; ++ptr)
+11
source

I typed a question, re-read it, and then I realized something very obvious that I forgot!

char evil[] = "HAL" 
char *ptr = evil;   
for (; *ptr != '\0'; ++ptr) {                       
    (*ptr)++;           
}   
printf("%s\n", evil);

It seemed like a trick.

+6
source

, , .

, , O (n ^ 2), n - . strlen() O (n), , '\0'. , , n strlen() , O (n ^ 2).

, strlen() . , , , strlen().

+5

C '\0'. , .

for (; *ptr != '\0' ; ++ptr) {
    /* ... */
}
+3

'\0'. , NUL .

+2

strlen(evil) . , strlen, , strlen: :

for (char *ptr = evil; *ptr; ++ptr) {             
    (*ptr)++;           
}
+2

This would do the trick:

char evil[] = "HAL";
*(int*) evil += 65793;
printf("%s\n", evil);
+1
source

Since we are talking about evil:

#include <stdio.h>

int main()
{
    char evil[] = "HAL";
    char *ptr;

    // Increment the pointer and its content in the same expression
    // Just to be really evil

    for (ptr = evil; *ptr != '\0'; ++*(ptr++)) { }

    printf("%s\n", evil);
}
+1
source

Source: https://habr.com/ru/post/1763999/


All Articles