0

Let's provide an example. I have one main file:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "otherfile.h"

char output[1024*10];

int main(){

    writeSomething(output);

    return 0;
}

and another file with the function:

void writeSomething(char *o){
    printf("sizeof(o)=%d", sizeof(o));
    //code
    memset(o,0,sizeof(o));
    // code
}

While compiling this, I got the warning:

argument to 'sizeof' in 'memset' call is the same expression as the destination; did you mean to provide an explicit length?

What I want is to set the whole output array to 0 in my function, so all 1024*10 bytes. But because I pass it as a pointer, it will only set the first 8 characters to 0 (because sizeof(o)=8).

How can I memset the whole array trough a pointer? Is that even possible?

moffeltje
  • 4,521
  • 4
  • 33
  • 57

1 Answers1

1

The problem is that when passed as the argument to the function, the array decays into a pointer and information about its size gets lost.

Redefine the function to

void writeSomething(char *o, size_t sz){
    printf("sizeof(o)=%d", sizeof(char) * sz);
    //code
    memset(o, 0, sizeof(char) * sz);
    // code
}

so that the call to it looks like writeSomething(output, 1024*10);.

As pointed out in the comments, the C99 standard requires that sizeof(char) be 1, so it's fine to omit the sizeof(char) in the code I provided. However, I prefer to leave it there for stylistic reasons.

blazs
  • 4,705
  • 24
  • 38
  • 2
    This is good, but `sizeof (char)` is always 1 so that part is pointless and just adds noise. Also the proper way to print values of type `size_t` is using `%zu`. – unwind Apr 06 '16 at 09:35
  • I know that `sizeof(char)==1` by the C99 standard, but I find it more "correct" to see that sizeof(char) there. It tells me that the programmer knows he's allocating the memory for `char`'s. – blazs Apr 06 '16 at 09:36
  • Its not just C99 where `sizeof(char)` is one. In all the C standards, it is one. – Spikatrix Apr 06 '16 at 10:23
  • I don't about pre-C99; I know that as of C99 it is 1. Thanks for noting. – blazs Apr 06 '16 at 10:24