Mostafa Mohsen Mostafa Mohsen - 27 days ago 6
C Question

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"

Answer

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