简体   繁体   中英

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]; You are assigning value at a[0] to a pointer. What you need is this.

counter = &(a[0]);

Or better

counter = a;

  1. counter = a[c];

Same as point#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. So You need to have a counter. So use c as the counter.

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';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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