簡體   English   中英

使用指針更改字符數組的字符

[英]changing characters of 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;
}

錯誤“退出非零狀態”

您需要以下內容

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]);

甚至以下

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


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

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

有三個問題。

  1. counter = a [0]; 您將[0]處的值賦給指針。 你需要的是這個。

counter =&(a [0]);

或更好

counter = a;

  1. counter = a [c];

與點#1相同。 你不必這樣做,因為計數器已經指向數組。 只需遞增指針即可。

  1. 由於您的數組長度為100,因此您只能存儲99個字符+空字符。 所以你需要一個櫃台。 所以用c作為計數器。

更改

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

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