C++

Ive got this code but it won't run and i can't find any more errors

int main(){
int *p, i, a[10];
p=a;
for (i=0; i<10; i++)
scanf("%d", p++);
printf("\n");
for (i=0; i<10; i++)
printf("a[%d]=%d\n", i, *p++);
return 0;
}
closed account (N8RzwA7f)
the formatting is terrible, but my best guess is the line with *p++ .
but i consider myself a beginner still in c++ so don't take my word for it.
maybe add parenthesis around it like so: (*p)++;
1
2
3
4
5
6
7
8
9
10
11
12
int main(){
  int *p, i, a[10];
  p=a;
  for (i=0; i<10; i++)
    scanf("%d", p++);
  printf("\n");

  p = a; // make p point to the beginning of the array
  for (i=0; i<10; i++)
    printf("a[%d]=%d\n", i, *(p++));
  return 0;
}


Note:
The topic of this thread is "C++", but this is merely C.
Last edited on
...but this is merely C.

If a C++ compiler compiles it, it is also a C++ program.
Pointers are error prone. You might want to consider using the subscript operator instead.
1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>

int main(){
	int i, a[10];
	for (i=0; i<10; i++)
		scanf("%d", &a[i]);
	printf("\n");
	for (i=0; i<10; i++)
		printf("a[%d]=%d\n", i, a[i]);
	return 0;
}
Last edited on
You need to reset your pointer to the beginning of the array.
Also it's better to use constants instead of magic numbers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main()
{
  const int NUM_ELEMS = 10 // #define NUM_ELEMS 10

  int *p, i, a[NUM_ELEMS];
  p = a; // same as p = &a[0]

  for (i=0; i < NUM_ELEMS; i++)
    scanf("%d", p++);

  printf("\n");
  
  // Reset p to the beginning
  p = a;
   
  for (i=0; i < NUM_ELEMS; i++)
    printf("a[%d]=%d\n", i, *p++);


  getch();
  return EXIT_SUCCESS;
}
Topic archived. No new replies allowed.