Nuggets10 Nuggets10 - 8 days ago 6
C Question

Simple C pointer program, not running

I have the following simple c program I am trying to run in CLion but is telling me that my char needs to be a pointer which I already have set as a pointer and declared to array abc so I am not sure what the issue is or how to debug it! The code was initially a sample for a lecture and I added the pointer declaration to see what happens when I run it. Any help would be appreciate.

#include <stdio.h>
#include <stdint.h>

int main() {
char *a;
char abc[5];
a = abc;
int i = 0;

while (1 == scanf("/%[^/ \t\n]", a[i++]))
printf(">%s<\n", a[i-1]);
}

Answer

Even though a is a pointer, a[i++] is not. In general, a[x] is equivalent to *(a + x), so in your case it is as if you had *(a + i++), where the * dereferences the pointer. You can use either &a[i++] to turn it back into a pointer, or a + i++.