Reputation: 3611
I am trying to get access the buffer called buf from function readfile. When I print sizeof(buf) I see that buf has 4 bytes (pointer). On the other hand, if I paste the printf command on the readFiles, I can see that the size is 2916. Actually, I don't understand why it is not 729, but it is obvious I cannot access the buf inside the readfile which I need. So the question is; where is the problem and how to correct it?
void readfiles(FILES * files){
unsigned char * buf [1*729];
int skip_lines = 14;
int shift = 0;
char * filename = "file.txt";
// printf("buf size %d", sizeof(buf));
readfile(filename, skip_lines, buf, shift);
}
int readfile(char * name, int skip, unsigned char * buf, int shift ){
// buf is (unsigned char *) on address 0x22dd18 ""
printf("buf size %d", sizeof(buf));
}
Upvotes: 1
Views: 503
Reputation: 83527
In readfile()
,
printf("buf size %d", sizeof(buf));
This prints 4 because buf is a pointer, as you seem to understand. The same print statement in readfiles()
. prints a larger number because there buf
is an array.
As pm100 stated, you cannot get the size of an array from a pointer to that array. Additionally, you need to be very careful about accessing pointers. If they do not point at a valid memory address, then you will have a lot of bugs. These are difficult to track down because the problems will occur in other parts of your code than where the pointer errors are. I suggest you learn about malloc()
and free()
in order to dynamically allocate memory for your pointers.
Upvotes: 0
Reputation: 50190
if you pass an array as a pointer into a C function you cannot detect its length.
int readfile(char * name, int skip, unsigned char * buf, int shift ){
// nothing you do in here can tell how big buf is
}
if you need to know the length of buf you have to pass it in as a paramter
int readfile(char * name, int skip, unsigned char * buf,int blen, int shift ){
...
}
Upvotes: 5