I was making a program that asked the user for a number and printed the number of points the user typed, but changing the grammatical number of the noun. For example: if I type "1", the program should print "1 point." and if I type "3" the program should print "3 points.".
The first thing I thought was to assign the different values inside the if statement:
Code:
#include <stdio.h>
#include <string.h>
int main(void) {
char noun[7];
int points;
printf("Type a number: ");
scanf("%i", &points);
if (points == 1) {
strncpy(points, "point", 6);
}
else {
strncpy(points, "points", 7);
}
printf("%i %s.\n", points, noun);
}
But this generates a "Segmentation fault" error, so I had an idea: declare two different strings and a pointer and assign their memory address inside the if statement:
Code:
#include <stdio.h>
#include <string.h>
int main(void) {
char singular[6] = "point";
char plural[7] = "points";
char *noun;
int points;
printf("Type a number: ");
scanf("%i", &points);
if (points == 1) {
noun = singular;
}
else {
noun = plural;
}
printf("%i %s.\n", points, noun);
}
This worked flawlessly, but I decided to search on the Internet another possible solution and I found this one here: c - assign a string of variable length in conditional statement - Stack Overflow
According to that answer, my code could be like this:
Code:
#include <stdio.h>
#include <string.h>
int main(void) {
char *noun;
int points;
printf("Type a number: ");
scanf("%i", &points);
if (points == 1) {
noun = "point";
}
else {
noun = "points";
}
printf("%i %s.\n", points, noun);
}
And this also worked. Now, here's my question: why can I assign a char pointer a string? I thought pointers were assigned a memory address. If I understood correctly, I can assign a pointer an array because an array is actually a pointer to its first element. And as strings are actually also arrays, I can assign a string to a pointer. But I can't do the following:
Code:
#include <stdio.h>
int main(void) {
int *numbers;
numbers = {1, 2, 3, 4}; /* Wrong */
for (int i = 0; i < 4; i++) {
printf("%i\n", numbers[i]);
}
}
Even using malloc() doesn't work:
Code:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *numbers = malloc(4 * sizeof(int)); /* Also wrong */
numbers = {1, 2, 3, 4};
for (int i = 0; i < 4; i++) {
printf("%i\n", numbers[i]);
}
free(numbers);
}
It cannot be assigned without specifying the index. So why can I assign a string to a pointer without specifying its index/length and why can't I do the same with a number?
I hope I've explained myself well, and thanks in advance.