views:

49

answers:

3

In C programming, how can a store a set of values entered by the user into an array using only pointers and no square brackets?

+1  A: 

X[Y] is exactly the same as *((X) + (Y)).

James McNellis
A: 
#include <stdio.h>


int main(int argc, char *argv)
{
  int i, *ip;

  static int a[] = {0,1,2,3,4,5,6,7,8,9,10,11};

  for(ip=a; ip < a+12; ip++)
    (*ip) *=2;  /* restore as number times 2 */

  putchar('\n');

  for(i=0; i < 12; i++)
    printf("%3d", a[i]);

  putchar('\n');



  return 0;
}

Result of restoring value * 2 to each element.

frayser@gentoo ~/doc/Answers/src/Haskell $ make array && ./array
cc     array.c   -o array

  0  2  4  6  8 10 12 14 16 18 20 22
Frayser
Making use of "entered by the user" values `for(ip=a; *ip++ = *argv++;);` will copy user input from `argv[]` to `a[].`
Frayser
+1  A: 

Try:

int  x??(??) = { 0,1 ,2 3, 4, 5, 6};

x??(2??) = 122;
Martin York