#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *ptr = (int*)malloc(15 * sizeof(*ptr)); /* a block of 15 integers */
if (ptr != NULL)
{
for(int i=1; i<=15; i++)
{
printf("Value of element [%d] is: %d\n",i, *(ptr+i) );
}
}
else
printf("Memory allocation is not sufficient");
}
Asked
Active
Viewed 42 times
0

cafce25
- 15,907
- 4
- 25
- 31

0x0040Coder
- 9
- 3
-
An array of 15 elements can be indexed from [0] to [14]. You are indexing from [1] to [15]. Also, your array is uninitialised, so this probably invokes undefined behaviour. – pmacfarlane Dec 27 '22 at 14:14
-
The more natural way to write `*(ptr + i)` is `ptr[i]`. – pmacfarlane Dec 27 '22 at 14:17
-
2@pmacfarlane, Re "*your array is uninitialised, so this probably invokes undefined behaviour*", Nit: For variables that can't be `register`, I think it's "merely" implementation-defined behaviour. But your point is that it's a bug, and that remains true. – ikegami Dec 27 '22 at 14:19
-
@cafce25 - Don't edit the errors being discussed out of the post. it confuses the issues for other attempting to address them in comments, and makes any answers posted obsolete. – ryyker Dec 27 '22 at 14:27
-
@cafce25 Your `ptr` seems to have reverted to being an int rather than an int *. And the formatting is terrible, sadly. – pmacfarlane Dec 27 '22 at 14:30
-
Nope that was the formatting treating `*...*` as bold or italics. OP used ` instead of (```) – cafce25 Dec 27 '22 at 14:31
-
@ryyker I admit fixing the indentation at the same time might have confused things and might have made it impossible to tell at a glance. – cafce25 Dec 27 '22 at 14:39
-
One more thing to consider... _[casting `malloc()` in C](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc)_. The first comment under the question in this post illustrates the rationale perfectly for why your cast should not be used here :). `stdlib.h` is used here, and so mitigates hidden errors, but still, the cast is not needed. – ryyker Dec 27 '22 at 16:25
-
Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Dec 28 '22 at 09:23
1 Answers
1
Going out on a limb here, since it's not really clear what the question is, but this doesn't really fit well in a comment. Maybe you want your loop to do this:
for (int i = 0; i < 15; ++i)
{
printf("Value of element [%d] is: %d\n", i + 1, ptr[i]);
}
This is because an array of 15 items is indexed from [0] to [14]. If you want to print the indices as 1 to 15, you can just add one when you print them as shown.
You still have the problem of the array being uninitialised. You could either use a loop to initialise them to something, e.g.
for (int i = 0; i < 15; ++i)
{
ptr[i] = i; // for example
}
or you could use something like memset(), if you want them to all be the same:
memset(ptr, 0, 15 * sizeof *ptr); // zero the array

pmacfarlane
- 3,057
- 1
- 7
- 24