Common C Programming Errors and Their Solutions
Error 1: Missing Semicolon
Code with Error:
int main() {
printf("Hello, World!")
return 0;
}
Correction: Add a semicolon after printf().
Fixed Code:
int main() {
printf("Hello, World!");
return 0;
}
Error 2: Using '=' instead of '==' in Conditions
Code with Error:
int main() {
int x = 5;
if (x = 10) {
printf("X is 10");
}
return 0;
}
Correction: Use '==' for comparison instead of '='.
Fixed Code:
int main() {
int x = 5;
if (x == 10) {
printf("X is 10");
}
return 0;
}
Error 3: Incorrect Array Indexing
Code with Error:
int main() {
int arr[5] = {1, 2, 3, 4, 5};
printf("%d", arr[5]);
return 0;
}
Correction: Array indexing starts from 0 and goes up to size-1.
Fixed Code:
int main() {
int arr[5] = {1, 2, 3, 4, 5};
printf("%d", arr[4]);
return 0;
}
Error 4: Dereferencing a NULL Pointer
Code with Error:
int main() {
int *ptr = NULL;
printf("%d", *ptr);
return 0;
}
Correction: Always check if a pointer is NULL before dereferencing.
Fixed Code:
int main() {
int *ptr = NULL;
if (ptr != NULL) {
printf("%d", *ptr);
}
return 0;
}