You are not logged in.

#1 2018-08-10 17:47:19

tony5429
Member
Registered: 2006-03-28
Posts: 956
Website

[SOLVED] Different Values Returned by sizeof()

Can anyone explain to me why sizeof(), if called within a function, returns 8 instead of 1000? And is there some other function I could use to allow the function to know the full length of the string?

C program:

#include <stdio.h>

void myfunction(char* instr) {
	printf("%i\n", sizeof(instr));
}

int main() {
	char mystr[1000];
	printf("%i\n", sizeof(mystr));
	myfunction(mystr);
}

Output:

1000
8

Last edited by tony5429 (2018-08-10 20:48:45)


Krondi: the free and ad-free music-streaming app.

Offline

#2 2018-08-10 17:55:16

mxfm
Member
Registered: 2015-10-23
Posts: 81

Re: [SOLVED] Different Values Returned by sizeof()

C tutorials often confuse arrays and pointers (because they try to explain in 'human' terms rather than what is written in language spec). What you ask is essentially C 101. You can find immediate answer to your question here (in particular, 6.10) and further information you can find in C std draft. Answer to your second question is also in linked faq.

Offline

#3 2018-08-10 17:56:16

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 20,122
Website

Re: [SOLVED] Different Values Returned by sizeof()

Sizeof is the compile time size, not determined at runtime.  In the main function, "mystr" is statically declared as 1000 bytes, so that's what sizeof returns, while "instr" is just a pointer - it could point to anything.  The pointer is 8 bytes.

You may want strlen instead - but that depends on what you are really trying to do.

Consider the following:

#include <stdio.h>

void myfunction(char *instr) {
	printf("%i\n", sizeof(instr));
}

int main() {
	char mystr[1000];
	printf("%i\n", sizeof(mystr));
	myfunction(mystr);

	char myotherstr[128];
	printf("%i\n", sizeof(myotherstr));
	myfunction(myotherstr);
}

Here two different things are passed to myfunction, but as stated above, "sizeof" is determined at compile time, so whatever sizeof(instr) is, it must be constant.  So even if the compiler were to try to infer the size of the memory area pointed to by instr, which memory area should it use?  The fact is the pointer passed to myfunction can have any number of bytes (or none at all).  But it is always a 8 byte pointer (at least on a 64 bit machine).

Last edited by Trilby (2018-08-10 18:00:16)


"UNIX is simple and coherent..." - Dennis Ritchie, "GNU's Not UNIX" -  Richard Stallman

Offline

#4 2018-08-10 20:48:33

tony5429
Member
Registered: 2006-03-28
Posts: 956
Website

Re: [SOLVED] Different Values Returned by sizeof()

Thank you for all the info mxfm and Trilby!


Krondi: the free and ad-free music-streaming app.

Offline

Board footer

Powered by FluxBB