0
#include <stdio.h>
#include <stdlib.h>
void main()
{
    int i;
    int *as[2];
    for(i=0;i<2;i++)
    {
        *as[i]=i;
        printf("%d\n",*as[i]);
    }
}

This is my code. I am expecting to print values 1 2

But when I run the code the console prints nothing. What have I done wrong?

  • where is as's allocated area? – snr Oct 29 '21 at 07:10
  • Thank you. This is what I was looking for. – Kishore Kumar S Oct 29 '21 at 07:33
  • You should probably have gotten a warning about this from the compiler... except that you don't. So, I've filed [this one](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=102996) against GCC and [this one](https://bugs.llvm.org/show_bug.cgi?id=52343) against clang. Which compiler were you using? – einpoklum Oct 29 '21 at 07:36

1 Answers1

0

The * character in C language is not a simple decoration. It declares a pointer that has to point to something. Here you declared an array of two pointers, but never initialized the pointer themselves. And dereferencing an uninitialized pointer is explicitely Undefined Behaviour (the hell for C programmers). If you want to process integers, get rid of the pointers:

int as[2];
for(i=0;i<2;i++)
{
    as[i]=i;
    printf("%d\n",as[i]);
}

Or if you really want to process pointers, ensure that they are initialized to point to a valid object:

int *as[2];
int data[2]
for(i=0;i<2;i++)
{
    as[i] = &(data[i]);   // Ok, as[i] now points to a valid integer
    *as[i]=i;
    printf("%d\n",*as[i]);
}

BTW, the idiomatic way to get the address of an element of an array would be:

    as[i] = data + i;
Serge Ballesta
  • 136,215
  • 10
  • 111
  • 230