This was the question asked to me in an interview in c:
#include<stdio.h>
void main(){
char *ch;
ch=fun1();
printf(ch);
}
fun1(){
char *arr[100];
strcpy(arr,"name");
return arr;
}
I was given the above program and was asked to figure out the problems in the above code.
below was my answer
- function declaration is wrong.the
return type should bechar ** - syntax of
printfis wrong arrscope is limited to the functionfun1
then
Interviewer : what would be your solution to the problem?
Me: you need to make the arr variable as global and fix the remaining issues mentioned above.
Interviewer: Dont you think global variables are dangerous?
Me: Yes ofcourse,since we cannot say where it is being accessed in which functions and sometimes it gets almost impossible to find which function has changed the value
Ineterviewer :give me a solution without a global variable
Me:????
what would be your solution for this?
Could anybody pls point out the errors that i have made !!
My solution could be
Here’s just what I found about the snippet …
I’d add a space before the header:
#include <stdio.h>; but that’s just for looksWRONG!
mainreturns anint. ALWAYS!And it should be one of:
int main(void)orint main(int argc, char **argv)if you need parametersNo prototype for
fun1in scope. This makes the compiler assume the function returns a value of typeintand the statement tries to assign that value to an object of typechar*which is illegal: the compiler must issue a diagnostic here.In C99, it is mandatory to specify a return type; in C89,
intis assumed. Also this function definition really should also be a prototype (in both C89 and C99) and specifiy the number and types of parameters (orvoidif it takes none).Why do you need an array of 100 pointers? ???
Oops … no prototype for
strcpy()in scope. Also, assuming thestrcpyis the one declared in<string.h>, the 1st parameter should be achar*not achar **arrceases to exist right after the function returns. Its address (the array decays to the address of its first element in this context) is unusable in the calling code.