Home > other >  Converting a C program to use pointers in array and have the same output
Converting a C program to use pointers in array and have the same output

Time:05-10

Here is the code, I am having trouble converting it to use pointers and have the same output:

#include <stdio.h>
int main() {
  int i, s[4], t[4], u = 0; 
  for (i=0; i<=4; i  ) 
    {
      s[i] = i;
      t[i] = i;
    } 
  printf("s : t\n");
  for (i = 0; i <= 4; i  ) 
  printf("%d : %d\n", s[i], t[i]);
  printf("u = %d\n", u);
 }```

The output of the code is this:

s : t
0 : 4
1 : 1
2 : 2
3 : 3
4 : 4
u = 0

My code is as follows, but the output isn't the same, can someone please help:


int main() {
  int i, 
    *s[4], 
    *t[4], 
    *u=0;
  for (i=0; i<=4; i  )
    {
      s[i] = &i;
      t[i] = &i;
    }
  printf("s:t\n");
  for(i=0;i<=4;i  )
    printf("%d:%d\n",*s[i],*t[i]);
printf ("u=%d\n", *u);
}

CodePudding user response:

Here is one possible solution that I am not sure if this might be what you are looking for:

#include <stdio.h>

int main() 
{
    int i, s[4], t[4], u=0;
    
    for (i=0; i<4; i  )
    {
      *(s i) = i;
      *(t i) = i;
    }
    printf("s:t\n");
    
    for(i=0; i<4; i  )
        printf("%d:%d\n",*(s i),*(t i));
    
    int *ptrToU = &u;
    printf ("u=%d\n", *ptrToU);
 }

Arrays in C are indexed starting at 0. Your loops had i<=4, but had to be changed to i<4 to prevent an out-of-bounds error.

In your original code, you had:

int *s[4];

This creates an array of 4 pointers to int. The question becomes, what do these pointers point to?

Your code:

s[i] = &i;

set each int pointer to point to the memory location of your variable i. Since i was not changing its memory location, every pointer in s[i] pointed to the same location. Hope this helps some.

  • Related