0

Hello I have this code that fills the array with a pointer and print it with a pointer as well. The result is faulse. Here is my code:

#include<stdio.h>
#include<stdlib.h>

int main(){
int p;
char po[8];
char *i;
i=po;
for(p=0; p<8; p++){
scanf("%c\n", i++);
}
for(p=0; p<8; p++){
printf("%c\n", *(i++));
}
return 0;
}

where is my fault?

1
  • 1
    scanf("%c\n", i++);...please don't write this sort of code. Commented Nov 28, 2015 at 13:40

3 Answers 3

1

There can be good reasons for increasing pointers. Simply do not forget to reset them to their initial value before reusing them!

Your code should be:

i=po;
for(p=0; p<8; p++){
scanf("%c\n", i++);
} /* i is now po + 8 ... */
i = po;
for(p=0; p<8; p++){
printf("%c\n", *(i++));
}

Now you should learn not to write such code:

  • blocks are not indented => harder to read
  • value of scanf is never tested: what happens on end of file (Ctrl-D on Unix-like, Ctrl-Z on Windows)?
  • not even one single comment...
Sign up to request clarification or add additional context in comments.

2 Comments

i = 0; will dereference NULL in the next printf.
Great you really helped! I am going to follow your tips! Also i thinking after ther for loop I have to reset the value of i like this 'i=po;'
1

i is already pointing at the end of the array. You want to print po using p as index:

for(p=0; p<8; p++){
printf("%c\n", po[p]);

Also, you don't need the \n in the scanf() call. Any whitespace character in format specifier will ignore all whitepaces in the input and as such you will need to input a non-whitespace character at the end to end the input.

2 Comments

With the command 'i=po;' i is pointing at the first element of the array po[8]. Right?
Yes, but only there. After that assignment, you increment i in the loop where you read input. So it doesn't point to po anymore after that.
0

The problem is that the pointer i being incremented in the first loop, will point to the end of the array at the end of the loop (more precise, at the next memory location after the one allocated for po, i.e. will point to po[8] which is not part of the array). You can add

i = po;

before the second loop, to make it point again to the beginning of po (to po[0]).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.