c语言中的纯指针表示法

  • 本文关键字:指针 表示 语言 c
  • 更新时间 :
  • 英文 :


我有这个编码分配,我必须使用纯指针符号。我几乎完成了它,但我刚刚意识到我使用了一个数组。我不允许这样做,除非我把它变成一个指针。这就是我有点卡住的地方。

这是我的代码。

#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] == '')
{
printf("Size too small");
exit(0);
}
if(s2_input[21] != '' )
{
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) = '';
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) = '';
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++;
}
}

我的问题是这一部分,我不确定如何编辑这个不包括数组,并且仍然以相同的方式输出程序。

if(s2_input[1] == '')
{
printf("Size too small");
exit(0);
}
if(s2_input[21] != '' )
{
printf("Size too big");
exit(0);
}

我试图在某一点上获取数组的地址,然后用指针对其解引用,但这仍然使用数组。这正是我想避免的。任何帮助将非常感激!

s2_input[i]可以写成*(s2_input+i),其中i是某个索引。

if ((s2_input[1]) == '')

等价于:

if (*(s2 + 1) == '')

表示对s2(即第0个[0]元素的位置)处的值进行解引用,并对其加1。

指针表示法和通常称为索引表示法(使用[ ]下标操作符)是完全等价的。这两种概念都提供了指针地址加上与该指针地址的偏移量。参见C11 Standard - 6.5.2.1数组下标array[offset]*(array + offset)1

例如,使用*array访问第一个元素是*(array + 0)的简写,即索引表示法中的array[0]0是原始指针地址的偏移量(在该类型的元素中)。(类型控制指针运算)

所以array[10]就是*(array + 10)。如果array类型为char,则array[10]地址比array地址晚10个字节。如果数组类型为int(其中int为4字节),则array[10]array地址(10-int)后40字节。

对于2D数组,arr2d[1][2]的表示法简单地表示为*(arr2d[1] + 2),进一步扩展为*(*(arr2d + 1) + 2)

一般来说,array[i]就是*(array + i),arr2d[i][j]就是*(*(arr2d + i) + j)

脚注:

  1. 由此可知,array[offset]等价于*(array + offset)等价于offset[array]

最新更新