1,468 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

3 Answers

Best answer
11 votes
11 votes
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
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

3 votes
3 votes
2 answers
2
8 votes
8 votes
2 answers
3
1 votes
1 votes
3 answers
4