0

How do I memset an array using a pointer to that array?

int *A, n;

printf("\n Enter the size of array : ");
scanf("%d",&n);

A = (int*) malloc(sizeof(*A) * n);

int i = 0;

memset(*A,5,n * sizeof(*A));

for(i = 0; i < n; i++)
    printf("%d ", A[i]);
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
  • 3
    The first argument to `memset()` must be a pointer. `*A` is an `int`, `A` is a pointer. – Barmar Mar 20 '20 at 00:57
  • 2
    You should have gotten a warning from that code. If not, turn up the warning level of your compiler. – Barmar Mar 20 '20 at 00:58
  • yes indeed i received an error which is: warning: passing argument 1 of 'memset' makes pointer from integer without a cast and also: expected 'void *' but argument is of type 'int' – java.begginer Mar 20 '20 at 01:08
  • 1
    Just change the first argument to `A`. – Barmar Mar 20 '20 at 01:09
  • 2
    BTW: [dont cast malloc](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Barmar Mar 20 '20 at 01:10
  • but it still doesn't initialize the array and just gives a garbage value, this is the result btw: Enter the size of array : 10 84215045, 84215045, 84215045, 84215045, 84215045, 84215045, 84215045, 84215045, 84215045, 84215045 – java.begginer Mar 20 '20 at 01:14
  • 1
    You're setting all the bytes to 5, not the integers. The 4 byte ints will have the hex value 0x05050505, which is 84215045 in decimal. – 1201ProgramAlarm Mar 20 '20 at 01:26
  • Hey, doesn't anyone wanna sum all this up in a nice, tidy "answer?" **:-)** – Mike Robinson Mar 20 '20 at 02:03

1 Answers1

1

The compiler doesn't emit warnings for no reason:

warning: passing argument 1 of 'memset' makes pointer from integer without a cast
expected 'void *' but argument is of type 'int'

This means that you are not passing the right type to the first argument of memset(), which indeed wants a pointer, while you are passing an integer.

Your pointer A is fine as is, dereferencing it (*A) is not needed and is wrong, the correct call is:

memset(A, 5, n * sizeof(*A));

More importantly though, this is not what you want to do! If you think the above sets all the elements of the allocated array to 5 that's not the case. Instead, memset() sets every single byte to 5 (see the manual page). Since an int is more than one byte (usually 4), this will fill your array with the value 0x05050505 (decimal 84215045) instead of 5.

In order to set every element to 5 you'll need a for loop:

int i = 0; 
for (i = 0; i < n; i++)
    A[i] = 5;

Finally, don't cast the return value of malloc():

A = malloc(sizeof(*A) * n);
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
  • So that's why it wont set all element to 5 even if I remove the indirection. Thank you so much for your help @Marco Bonelli. It helped me a lot to understand what I am doing. – java.begginer Mar 20 '20 at 04:06