Consider this char* example:
char* s;
s = (char*) malloc(5 * sizeof(char));
s = "Hello";
for (int i = 0; i < 5; i++)
{
printf("%c", s[i]);
}
printf("\n%s", s);
The code above shows two ways of printing the same thing: "Hello".
I tried to find an equivalent for int* and this is the best I could come up with:
int* ptr;
ptr = (int*) malloc(5 * sizeof(int));
ptr[0] = 2;
ptr[1] = 3;
ptr[2] = 3;
ptr[3] = 3;
ptr[4] = 4;
for (int i = 0; i < 5; i++)
{
printf("%i ", ptr[i]);
}
printf("\n%d", *ptr);
The first printf in the second example prints the whole array (2, 3, 3, 3, 4), but the second one only prints the first int value in the array (2).
How can I change the second printf for me to get the whole array? Also, how can I initialize the dynamically allocated array in one line? I tried ptr = {2, 3, 3, 3, 4}
, but I got "error: expected expression".
I know in Python one can very easily initialize and print an array like this:
arr = [2, 4, 5, 7, 9]
print("The Array is: ", arr) #printing the array
What's the equivalent of that in C?