Question:
C Programming Plz explain me in detail thxs plz tell me whether its runtime error or compile time error?
Saurabh S
2010-07-24 10:31:49 UTC
main()
{ int *p=10;
printf("%d\n",*p);
}
a) 10
b) run time error
c) compiler error
d) 5
ans:b (?)
Four answers:
Beau
2010-07-24 12:06:44 UTC
This is what makes C such a flexible language; it will let you do things that don't even make sense to the people who wrote the compiler. All in all, if you know what you are doing in C you can write anything pretty much. Whats wrong with this code though? You are assigning an integer value to a pointer without casting it. The correct way to write this code (assuming you meant to put the value '10' in the memory pointed to by p) would be something like:



int *p = (int *) malloc(sizeof(int));

*p = 10;

printf("%d\n",*p);



then later free the allocated memory of course.



Doing this will cause undefined behavior, just as referencing a null pointer does. The correct answer is B.
peteams
2010-07-24 23:31:33 UTC
Depending on your environment it will either be (b) runtime error or (e) none of the above (or actually (c) compiler error if the compiler has any sense and prevents silly things early on).



int *p = 10; // assigns p as a pointer to int to address 10.

printf("%d\n", *p); // dereferences address 10 as an integer.



One of two things will occur during the printf. Firstly 10 is probably not a valid memory address, or at least not one a humble program is allowed to look at, so you will get a protection fault, that is a runtime error. Secondly 10 may be a valid memory address, but the changes of it containing 10, 5 or anyother given number are remote (probably exactly 2 to the power 32 on a 32-bit machine), hence (e) none of the above.
Srikanth
2010-07-25 04:25:04 UTC
hi. it is run time error (in some compliers like c-free). because here 10 is integer. where as p is integer pointer. pointer can store the address of the another variable. here conversion of int to int * makes an error.



Note in some compilers (tc3) 10 is taken as address and prints the some garbage value which having the address is 10. if you write printf("%d\",p); it gives the output 10.
?
2010-07-24 17:43:19 UTC
Off the top of my head I'm going to say C, but I've been working with java for too long so I might be muddled.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...