in Programming
891 views
6 votes
6 votes

Consider the following two C codes:

Code 1 Code 2
char *a = "hello world";
printf(a);
char a[] = "hello world";
printf(a);
  1. Both are valid C codes
  2. Code 1 is valid but not code 2
  3. Code 2 is valid but not code 1
  4. Both codes are not valid in C
in Programming
by
891 views

3 Answers

11 votes
11 votes
Best answer
char *a = "hello world";
printf(a);

char a[] = "hello world";
printf(a);

Both are valid. In first case, programmer is not supposed to modify the contents being pointed to by a as "hello world" is a string literal. In second case, "hello world" is copied to an array a, in the function call space and hence can be modified by the programmer. For printf case, both works the same.

PS: The first argument to printf must be a character pointer and all its characters are printed with format specifiers taken care of separately. So, we do not need %s if we want to just print a string. Avoiding it is actually better for performance reason.

edited by

4 Comments

IN STATEMENT 2

A is just mnemonic , it is not variable .so how can we print(A) ??
0
0
while printing, how printf will know that it have to print as %c or %s. I mean how printf will know what to print - string or a character.

because in both case a is pointing to a single character(1st character)
0
0
First argument to printf is const char * -- means it is always treated as a string.
2
2
0 votes
0 votes
option (a) is correct

because pointer and array both are similar in a language .

the diffrence is that pointer is a variable and array is a newmonic .

both declration is correct
0 votes
0 votes

In C, arrays and pointers are identical in the way they access the memory.

Hence, Option A


The major difference, however, is that the pointer identifier can take different values if we assign them to it. But the name of the array points to the base address of the array, and it can't be changed.

In plain English, a pointer A is a variable, while the array name A would be a const int*.

Answer:

Related questions