Pointer arithmetic on argv elements (Turbo C / DOS): adding pointers is invalid and causes a compile-time error.\n\n/* sample.c /\n#include <stdio.h>\n\nint main(int argc, char argv[])\n{\n int j;\n j = argv[1] + argv[2] + argv[3];\n printf("%d", j);\n return 0;\n}\n\nInvoked as: sample 1 2 3

Difficulty: Easy

Correct Answer: Error

Explanation:


Introduction / Context:
This question checks your understanding of pointer arithmetic rules in C. While pointers can be incremented or decremented by integers to traverse arrays, adding two pointers to each other is not a valid operation and will be rejected by the compiler.


Given Data / Assumptions:

  • argv is an array of char pointers to strings.
  • The code attempts j = argv[1] + argv[2] + argv[3].
  • Compiler model: Turbo C (DOS) style, but the rule is the same across conforming C compilers.


Concept / Approach:
Legal pointer arithmetic allows expressions like ptr + integer or ptr - integer (to move within the same array) and ptr1 - ptr2 (to compute distance within the same array). However, ptr1 + ptr2 is invalid because the result has no well-defined meaning in C. A conforming compiler diagnoses this as an error at compile time.


Step-by-Step Solution:

Identify types: argv[1], argv[2], argv[3] are char.Expression char* + char* is illegal → compilation fails.Because the program does not compile, it produces no runtime output.


Verification / Alternative check:
Replacing the line with int j = atoi(argv[1]) + atoi(argv[2]) + atoi(argv[3]); compiles and prints 6 for the given invocation.


Why Other Options Are Wrong:

  • 6 / sample 6 / Garbage value: All imply successful compilation and execution.


Common Pitfalls:
Assuming pointers behave like integers in all arithmetic contexts; forgetting that only pointer±integer and pointer–pointer (same array) are permitted operations.


Final Answer:
Error

More Questions from Command Line Arguments

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion