-1

My program is as follows

#include<stdio.h>

int *intial(int);

int main (void)
{
    int i, *b;

    b=intial(5);
    for(i=0;i<5;i++)
        printf("%d\t",*(b+i));
    getch();
}

int *intial(int t)
{
    int i, *a; 

    for(i=0;i<t;i++)
        a[i]=i;
    return a;
}

But i am getting garbage values.

I also tried this

int *intial(int t)
{
    int i, a[10];

    for(i=0;i<t;i++)
        a[i]=i;    
    return a;
}

But it is not working.

ShuklaSannidhya
  • 8,572
  • 9
  • 32
  • 45
user1275375
  • 1,361
  • 5
  • 23
  • 38
  • 4
    Where do you expect `a` to point to without initializing it? Pointers are not magic... –  Jul 19 '13 at 10:24
  • 3
    Undefined behaviour because `a` is not allocated. Try `int *a = malloc(t * sizeof(int));`. And remember `free(b)` before your program exits. – johnchen902 Jul 19 '13 at 10:24
  • 3
    possible duplicate of [why does this function return garbage value](http://stackoverflow.com/questions/12042538/why-does-this-function-return-garbage-value) and 625482976472 similar questions. –  Jul 19 '13 at 10:25
  • 6
    Bleeeech ... What's that coding style ? Radom indentation, weird stuff etc etc ... How do you expect us to actually READ this ? – Mathuin Jul 19 '13 at 10:25
  • I answered a similar question (not duplicate) in the past: http://stackoverflow.com/a/8779787/509868 – anatolyg Jul 19 '13 at 11:43

2 Answers2

3

In order to work properly, your function should read

int *intial(int t)
{
    int i;
    int *a = malloc(t * sizeof(*a));
    if (!a) return NULL; // error checking
    for(i=0;i<t;i++) {
        a[i]=i;
    }
    return a;
}

The "calling treaty" for this function is that the pointer returned is a malloc()ed one which the caller has the obligion for to free() it.

Of course, the caller as well should do proper error checking:

int main()
{
    int i;
    int *b;
    b=intial(5);
    if (!b) {
        fprintf(stderr, "Malloc error.\n");
        return 1;
    }
    for(i=0;i<5;i++) {
        printf("%d\t",*(b+i)); // *(b+i) should be replaced with b[i] for readability
    }
    free(b); // free the memory
    return 0;
}
glglgl
  • 89,107
  • 13
  • 149
  • 217
2

You need to allocate memory for your array with malloc(). Otherwise a, and hence b, will not point to anything in particular.

Sneftel
  • 40,271
  • 12
  • 71
  • 104