1,580 views
3 votes
3 votes
#include <stdio.h>
#include <string.h>
void fun(char *arr)
{
int i;
unsigned int n = sizeof(arr);
printf("n = %d\n", n);
for (i=0; i<n; i++)
 printf("%c ", arr[i]);
}
// Driver program
int main()
{
char arr[] = {'k', 'h', 'u', 's', 'h', 'a', 'l'};
fun(arr);
return 0;
}

2 Answers

1 votes
1 votes
When passing an array as an argument to a function, a fixed array decays into a pointer, and the pointer is passed to the function.

#include <stdio.h>
#include <string.h>

void fun(char *arr)
{
int i;
unsigned int n = sizeof(arr); //This will give size of pointer. On different machines it can be a different size(on mine Its 4)
printf("n = %d\n", n);  // n=4
for (i=0; i<n; i++)
 printf("%c ", arr[i]);  
}

int main()
{
char arr[] = {'k', 'h', 'u', 's', 'h', 'a', 'l'};
fun(arr);
return 0;
}

 

output will be

4

k h u s
edited by
0 votes
0 votes

Here in this snippet the main driver function is passing the pointer to the integers and thus its is returning the size of the pointer only not the array: the underlying concept is: " If we pass an array to a function its the address of first element plus the data size that is passed to function ".
But when you check the size of an array in main program itself then its the total size that is evaluated and thus it will return the total size.

Related questions

1 votes
1 votes
0 answers
1
Akshay Nair asked Jan 29, 2018
445 views
What is the output of the following program?void main(){printf("%d",5%2);printf("%d",-5%2);printf("%d",5%-2);printf("%d",-5%-2);printf("%d",2%5);}A) 1,-1 -1 1 0B)1 -1 1 -...
2 votes
2 votes
2 answers
2
Khushal Kumar asked Jul 8, 2017
1,375 views
int main(){ int a = 3, b = -8, c = 2; printf("%d", a % b / c); return 0;}
2 votes
2 votes
2 answers
3
Khushal Kumar asked Jul 8, 2017
1,286 views
#include<stdio.h int main(void){ int a = 1, 2, 3; printf("%d", a); return 0;}
1 votes
1 votes
1 answer
4
Khushal Kumar asked Jul 7, 2017
343 views
#include <stdio.h>int main(){char a = '\'';printf("%c", a);return 0;}