Thread: please help me i trying to print array elements but it printing some junk values

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    4

    Red face please help me i trying to print array elements but it printing some junk values

    please help me i trying to print array elements but it printing some junk values

    #include<stdio.h>
    #include<conio.h>
    int *fun()
    {
    int i[]={1,2,3,4,5};
    return &i[0];
    }
    void main()
    {
    int *p;
    int i;
    clrscr();
    p=fun();
    for(i=0;i<5;i++)
    {
    printf("%d\n",*(p+i));
    }
    getch();
    }

  2. #2
    Registered User
    Join Date
    Oct 2010
    Location
    Vancouver
    Posts
    5
    It looks to me like you are printing out the address of array[0]...it also appears that you are trying to return the address of a local variable...

  3. #3
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    fun() is returning an address that is being popped off the stack (and therefore is no longer valid memory). If you want to do something like that, you need to declare the array as static, or dynamically allocate memory for it with malloc().
    bit∙hub [bit-huhb] n. A source and destination for information.

  4. #4
    Registered User
    Join Date
    Oct 2010
    Posts
    4
    yes i got it
    I as to declare it as static / dynamic
    Thank you

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 12
    Last Post: 03-11-2010, 02:28 PM
  2. Replies: 7
    Last Post: 02-25-2010, 11:38 AM
  3. warning: excess elements in array initializer
    By redruby147 in forum C Programming
    Replies: 6
    Last Post: 09-30-2009, 06:08 AM
  4. Personal Program that is making me go wtf?
    By Submeg in forum C Programming
    Replies: 20
    Last Post: 06-27-2006, 12:13 AM
  5. Using write() to print array elements
    By Unregistered in forum C Programming
    Replies: 1
    Last Post: 04-01-2002, 09:18 PM