C语言纯指针编程:将数组下标访问改为纯指针写法
问题:替换数组下标访问为纯指针表示法
作业要求代码仅使用纯指针表示法,目前代码基本完成,但以下片段使用了数组下标访问,需要改为纯指针写法且保持功能不变,试过取地址解引用但仍觉得涉及数组,求帮助。
待修改代码片段:
if(s2_input[1] == '\0') { printf("Size too small"); exit(0); } if(s2_input[21] != '\0' ) { printf("Size too big"); exit(0); }
解决方案
在C语言中,array[n]的本质就是*(array + n)——数组下标语法只是指针偏移解引用的语法糖。直接把下标访问替换成指针偏移的解引用形式,就完全符合纯指针表示法的要求,不会用到数组下标语法。
直接替换的简洁写法
修改后的代码片段:
if(*(s2_input + 1) == '\0') { printf("Size too small"); exit(0); } if(*(s2_input + 21) != '\0' ) { printf("Size too big"); exit(0); }
另一种纯指针移动风格(可选)
如果想要完全通过指针移动而非数字偏移的方式实现,也可以这样写:
// 检查输入长度过小:第二个字符就是结束符,说明输入为空或只有一个字符 char *check_ptr = s2_input; check_ptr++; // 移动到第二个位置 if(*check_ptr == '\0') { printf("Size too small"); exit(0); } // 检查输入长度过大:第22个位置(索引21)不是结束符,说明输入超过20个字符 check_ptr = s2_input; for(int i = 0; i < 21; i++) { check_ptr++; } if(*check_ptr != '\0') { printf("Size too big"); exit(0); }
第一种写法更简洁高效,且完全满足纯指针要求,因为*(s2_input + 1)是纯粹的指针操作,没有使用数组下标[]语法。
修改后的完整代码
#include <stdio.h> #include <stdlib.h> /* Function Prototypes */ int main(); void s1(char *random); void s2(char *s2_input, int index); void strfilter(char *random, char *s2_input, char replacement); int main() { for(;;) { int s1_index = 41; char s1_random[s1_index]; s1(s1_random); printf("\ns1 = "); puts(s1_random); printf("s2 = "); int s2_index = 21; char s2_input[s2_index]; s2(s2_input, s2_index); // 改为纯指针写法 if(*(s2_input + 1) == '\0') { printf("Size too small"); exit(0); } if(*(s2_input + 21) != '\0' ) { printf("Size too big"); exit(0); } printf("ch = "); int replacement = getchar(); if(replacement == EOF) break; while(getchar() != '\n'); printf("\n"); strfilter(s1_random, s2_input, replacement); printf("\ns1 filtered = "); puts(s1_random); printf("Do you wish to run again? Yes(Y), No(N) "); int run = getchar(); // or include ctype.h and do: // run == EOF || toupper(run) == 'N' if(run == EOF || run == 'N' || run == 'n') break; while(getchar() != '\n'); } } void s1(char *random) { int limit = 0; char characters; while((characters = (('A' + (rand() % 26))))) /* random generator */ { if(limit == 41) { *(random + 41 - 1) = '\0'; break; } *(random + limit) = characters; limit++; } } void s2(char *s2_input, int index) { char array[21] = "123456789012345678901"; /* populated array to make sure no random memory is made */ char input; int count = 0; int check = 0; while((input = getchar() )) { if(input == '\n') { *(s2_input + count) = '\0'; break; } else if(input < 65 || input > 90) { printf("invalid input"); exit(0); } *(s2_input + count) = input; count++; } index = count; } void strfilter(char *random, char *s2_input, char replacement) /* replacement function */ { while(*s2_input) { char *temp = random; while(*temp) { if(*temp == *s2_input) *temp = replacement; temp++; } s2_input++; } }
内容的提问来源于stack exchange,提问作者user20544996
相关产品推荐
相关产品推荐

