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]); 
8
  • 3
    The first argument to memset() must be a pointer. *A is an int, A is a pointer. Commented Mar 20, 2020 at 0:57
  • 2
    You should have gotten a warning from that code. If not, turn up the warning level of your compiler. Commented Mar 20, 2020 at 0:58
  • 1
    Just change the first argument to A. Commented Mar 20, 2020 at 1:09
  • 2
    BTW: dont cast malloc Commented Mar 20, 2020 at 1:10
  • 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. Commented Mar 20, 2020 at 1:26

1 Answer 1

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); 
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.