C Code Snippets 8 - Returning Pointers From a Function

Hello everyone, sometimes it can be hard to figure out how to use pointers with functions. In order to get rid of the confusion, I am sharing a code snippet that returns a pointer from a function.


* Author : Berk Soysal

#include <stdio.h>

float* maxAddress(float a[], int size){
  float  max =  a[0];
  float *maxAddr = &a[0];
  int i;
  for(i=0; i<size; i++){
    if(a[i] > max){
      max =  a[i]; // max value
      maxAddr = &a[i]; // max address
  return maxAddr;

int main()
  float x[6] = {1.9, 3.3, 7.1, 5.4, 0.2, -1.5};
  float *p;
  int k;
  // print the index, value and the address
  for(k=0; k<6; k++){
    printf("%d  %f  %p\n", k, x[k], &x[k]);

  p = maxAddress(x,6);
  int y = (p-&x[0]);

  printf("\nMaximum Value: %f\n", *p);
  printf("Its Address: %p \n",  p);
  printf("Its Index: %d \n", y);

  return 0;


Keywords: CCode Snippets 

Software Developer, Codemio Admin

Disqus Comments Loading..