Thread: Funciton pointer and array varaible assignment

  1. #1
    Registered User
    Join Date
    Mar 2008
    Location
    India
    Posts
    133

    Funciton pointer and array varaible assignment

    Hi ,

    I am doing one sample program with function pointer.

    Missing part for me is how bags array first index is getting replaced .
    Line number 10 calls function next , but how come value getting changed in bags arrary.

    Below is the code.

    Code:
     1#include <stdio.h>
     2#include <stdlib.h>
     3
     4int bags[5]={20,5,20,3,20};
     5
     6main(void)
     7{
     8  int pos=15,*next();
     9  printf("%d %d\n",bags[0],bags[1]);
    10  *next()=pos;
    11  printf("%d %d %d",pos,*next(),bags[0]);
    12}
    13
    14
    15
    16int *next()
    17{
    18  int i;
    19  for (i=0;i<5;i++)
    20    if (bags[i]==20)
    21      {
    22         return (bags+i);
    23      }
    24  printf("Error!");
    25  exit(0);
    26}
    output:
    20 5
    15 20 15

    Any inputs on this would be highly appreciated.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,749
    > Line number 10 calls function next , but how come value getting changed in bags arrary.
    Because
    a) you returned a pointer
    b) you dereferenced that pointer
    c) you have an assignment.

    Line 10 is just a long winded way of saying
    bags[0] = pos;
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Mar 2008
    Location
    India
    Posts
    133
    Thanks for the reply.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Definition of funciton.
    By KOFI in forum C Programming
    Replies: 2
    Last Post: 04-13-2010, 10:59 AM
  2. Pointer assignment using array name
    By stavos77 in forum C Programming
    Replies: 7
    Last Post: 03-12-2010, 03:12 PM
  3. Passing an array in a funciton
    By jordanguyoflove in forum C Programming
    Replies: 5
    Last Post: 03-31-2009, 10:15 AM
  4. varaible help...?
    By Rune Hunter in forum C++ Programming
    Replies: 30
    Last Post: 09-13-2004, 06:58 PM
  5. need help for getline() funciton
    By condorx in forum C++ Programming
    Replies: 2
    Last Post: 10-05-2003, 01:55 PM

Tags for this Thread