C Programming Interview Questions
This page consists of C Programming interview questions and answers.
For this we can write the following code.
#include <stdio.h>
int main() {
if ( printf("Hello World") ) { }
return 0;
}
Or we can write the following.
#include <stdio.h>
int main() {
if ( printf("Hello World") );
return 0;
}
Note! The printf()
function will return the total number of characters printed and we can use this inside the if-statement to print the message "Hello World" without using a semicolon.
If a pointer is assigned the NULL value then it becomes a NULL pointer. A NULL pointer points nowhere.
Following is an example of a NULL pointer.
int *ptr = NULL;
Any pointer that does not points at a valid memory address is called a dangling pointer.
In the following code we are creating a dangling pointer.
#include <stdio.h>
#include <stdlib.h>
int main() {
// integer variable i
int i = 10;
// allocate memory to integer
// pointer
int *ptr = (int *) malloc (1 * sizeof(int));
// assign address of integer
// variable to integer pointer
// variable
ptr = &i;
// this is now a dangling pointer
free(ptr);
// this will not work
printf("value of i = %d\n", *ptr);
return 0;
}
malloc()
and calloc()
in C programming?Both are used to allocate memory space but calloc()
by default fills the allocated memory space with 0.
Click here to learn more about malloc and calloc.
The base address means the starting address of an array.
C code:
int arr[] = {10, 20, 30, 40, 50};
int c = 5;
int i = 0;
while (i < c) {
printf("%d\n", arr[i % 2 == 0 ? i : i - 1]);
i++;
}
The above code will print the following.
10
10
30
30
50
In the above code we are using the ternary operator. If i is even the code is printing the value pointed by i in the array arr.
If i is odd the code is printing the value pointer by (i - 1) in the array arr.
A variable whose value will not change is called a constant.
We can write the following code to create a constant in C programming language.
const int num = 100;
To match a pattern in a given string we can use the strstr
function.
We can write the following C code to check the pattern.
#include <stdio.h>
#include <string.h>
int main() {
char *str = "Hello World";
char *ptrn = "lo";
if (strstr(str, ptrn)) {
printf("Pattern '%s' is present in string '%s'.\n", ptrn, str);
} else {
printf("Pattern not found.\n");
}
return 0;
}
ADVERTISEMENT