-1

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?

1 Answers1

1

No,In C you cannot print array with single line of code, there is no inbuilt function available in C to print the array in single line.

Python also doesn't print array in single line, it does use loops but those functions are not visible to us.

How ever there are ways by which we can print C array without for-loop, You can refer this Question answered in stack overflow for that.

Is printing array possible without any loop in the C Language?

Vikash PR
  • 66
  • 7
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/31005855) – Artemis Feb 07 '22 at 11:07
  • @Artemis I thought links to other SO answers were OK? – Jack Deeth Feb 07 '22 at 16:06
  • 2
    @JackDeeth Not if it's only a link. Stack Overflow answers can be removed too. Voting to close as duplicate is more appropriate here. – Gert Arnold Feb 07 '22 at 21:17