C Programming: Arrays, Structs, and Pointers Explained
Classified in Computers
Written on in
English with a size of 3.22 KB
1. Defining a Car Structure in C
Define a structure suitable for the following details of a car: Brand, Category (compact, family), Model, Engine Size, and Year.
Answer:
struct Datos_auto {
char brand[30];
char model[10];
char category[30];
int year;
int size;
};4. Array Index Out of Bounds
What happens if you assign a value to an element of an array whose index exceeds the array size?
Answer: It will overwrite data in adjacent memory locations.
5. Array Name Representation
If an array is declared as int list[12];, what does the word list represent?
Answer: It represents the array name (which also acts as a pointer to the first element).
6. Definition of a String in C
In the C language, what is a string?
Answer: A string is a composite data type, specifically an array of characters terminated by a null character ('\0').
7. Accessing String Subsets
Assuming the statement char str[] = "Montenegro";, what code would write the last 5 letters ("negro") to standard output?
Answer:
int i;
for (i = 5; i <= 9; i++) {
printf("%c", str[i]);
}8. Understanding Pointers
What is a pointer?
Answer: A pointer is the address of a variable. It is a variable like any other that contains a memory address pointing to another location in memory where data is stored.
9. Benefits of Using Pointers
Mention two good reasons for using pointers.
Answer:
- It makes it easy to manipulate arrays.
- It allows for efficient memory management.
10. Referencing Array Elements
Assuming a declaration of an array with 10 elements named table, state two ways to refer to the third element.
Answer: table[2] or *(table + 2).
11. 2D Array and Pointer Notation
Given static int arr[2][3] = {{10, 11, 12}, {13, 14, 15}};, provide a reference to the element 14 using array notation and pointer notation.
Answer:
- Array notation:
arr[1][1] - Pointer notation:
*(*(arr + 1) + 1)
12. Function to Swap Two Integers
Write the code for a function to swap two variables of type int.
Answer: Assuming v1 and v2 are declared as global variables:
void swap() {
int temp;
temp = v1;
v1 = v2;
v2 = temp;
}13. Summing Array Elements with Pointers
Given static float list[] = {1.0, 2.0, 3.0, 4.0, 5.0};, enter the code to determine the sum using pointers.
Answer:
float sum;
float list[] = {1.0, 2.0, 3.0, 4.0, 5.0};
sum = *(list + 0) + *(list + 1) + *(list + 2) + *(list + 3) + *(list + 4);