简体   繁体   English

使用指针更改字符数组的字符

[英]changing characters of character array using a pointer

its not that complicated, my problem is i don't understand how to change the variable of a character array using a pointer 它不是那么复杂,我的问题是我不明白如何使用指针更改字符数组的变量

#include "stdio.h"

int main(void) {
// Disable stdout buffering
setvbuf(stdout, NULL, _IONBF, 0);

char a[100], ch, *counter;
int c = 0, i;

counter = a[0];
printf("please enter a sentance:");


while ((ch = getchar()) != '\n'){
    printf("yo");
    *counter = ch;     //problem is here
    counter = a[c];
    c = c + 1;
}
printf("hi\n");

for(i = c-1; i >= 0; i--){
    printf("%c", a[i]);
}

return 0;
}

the error is "exited with non zero status" 错误“退出非零状态”

You need the following 您需要以下内容

counter = a;
^^^^^^^^^^^
printf("please enter a sentance:");


while ((ch = getchar()) != '\n'){
    printf("yo");
    *counter++ = ch;     //problem is here
    ++c;
}

while ( c != 0 ) printf("%c", a[--c]);

Or even the following 甚至以下

counter = a;
^^^^^^^^^^^
printf("please enter a sentance:");


while ((ch = getchar()) != '\n'){
    printf("yo");
    *counter++ = ch;     //problem is here
}

while ( counter != a ) printf( "%c", *--counter );

There are three issues. 有三个问题。

  1. counter = a[0]; counter = a [0]; You are assigning value at a[0] to a pointer. 您将[0]处的值赋给指针。 What you need is this. 你需要的是这个。

counter = &(a[0]); counter =&(a [0]);

Or better 或更好

counter = a; counter = a;

  1. counter = a[c]; counter = a [c];

Same as point#1. 与点#1相同。 You dont have to do this as counter is already pointing to array. 你不必这样做,因为计数器已经指向数组。 Just increment the pointer. 只需递增指针即可。

  1. Since you have array of length 100, you can store only 99 characters + a null charecter. 由于您的数组长度为100,因此您只能存储99个字符+空字符。 So You need to have a counter. 所以你需要一个柜台。 So use c as the counter. 所以用c作为计数器。

Change 更改

while ((ch = getchar()) != '\n'){
    printf("yo");
    *counter = ch;     //problem is here
    counter = a[c];
    c = c + 1;
}

to

i = 0;
while ((ch = getchar()) != '\n' && ((sizeof(a)/sizeof(a[0])-1)>c)){
    printf("yo");
    *counter = ch;
    counter++;
    c++;
}
*counter = '\0';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM