C pointers and array

#include <stdlib.h> #include <stdio.h> int main (void) { int a[] = {1,2,3,4,5}; int b[] = {0,0,0,0,0}; int *p = b; for (int i =0; i < 5; i++) { b[i] = a[i]+1; *p = a[i]+1; p++; } for (int i = 0; i < 5; i++) { printf (" %i \t %i \t %i \n", *p++, b[i], a[i]); } return 0; } 

For this code, I understand why the output is for a and b, but why does the pointer have the same meaning?

* p is b [0] = a [0] +1, right? So p ++ means the next address for b, so b [1] = a [1] +1.

 ie *pba 1 2 1 2 3 2 3 4 3 4 5 4 5 6 5 
+7
source share
4 answers

You get undefined behavior. At the end of the first cycle, p indicates "one end" b . Without restarting it, you then cast it and continue to increase it, both of which cause undefined behavior.

It is possible that in your implementation, array a is stored immediately after array b and that p began to point to array a . This will be one of the possible "undefined" bahaviour.

+9
source

after the first for {}, p points in b [5], but the size of b is 5, so the value of b [5] is unknown, printf * p is the same value as [i], the reason may be in the memory b [ fifty].

+1
source

I think you need to add p = p - 5;

 #include <stdio.h> int main (void) { int a[] = {1,2,3,4,5}; int b[] = {0,0,0,0,0}; int *p = b; int i =0; for (i =0; i < 5; i++) { b[i] = a[i]+1; *p = a[i]+1; p++; } p = p - 5; for (i = 0; i < 5; i++) { printf (" %i \t %i \t %i \n", *p++, b[i], a[i]); } return 0; } 
+1
source

you should not create a separate cycle for printing and increase the values โ€‹โ€‹of the array. do both in the same loop and do follouwing to get ur output :) # include #include

 int main(void) { int a[]={1,2,3,4,5}; int b[]={0,0,0,0,0}; int c[]={0,0,0,0,0}; int *p; int i; p=c; for( i =0 ; i<5 ; i++) { b[i]=a[i]+1; *p=b[i]-1; //*p++; //for( i =0 ; i<5 ; i++) printf(" %i \t %i \t %i \n" ,*p,b[i],a[i]); } return 0; } 
-2
source

All Articles