sizeof "string"

mark at elsie.UUCP mark at elsie.UUCP
Fri Jan 27 23:36:20 AEST 1984


There is a subtle difference between arrays and pointers to arrays. Take the
following test program:

    char		dbuf[] = "1234567890";
    main()
    {
    char		buf[10];
    char		*cbuf = "1234567890";

    printf("bufsz= %d, cbufsz= %d, dbufsz= %d\n",
	    sizeof buf, sizeof cbuf, sizeof dbuf);
    }

outputs: "bufsz= 10, cbufsz= 4, dbufsz= 11" (we have a 32 bit machine).
"buf[10]" allocates 10 bytes of space, with "buf" pointing to the first
location. "*cbuf" allocates a pointer, cbuf, that points to the string
"1234567890"; "sizeof cbuf" thus is the size of the pointer. "dbuf[] = .."
(which must be an external to be initiallized) is an array containing the
string "1234567890\0" (the NULL at the end of the string is the 11th byte).
Dbuf, and buf are the same, while cbuf is different; at least as far as
sizeof is concerned. Note also that "&cbuf" is a meaningful construct while
"&buf" and "&dbuf" are not. The important point to note here is that while
arrays and pointers to arrays are very similiar, they are not the same.


-- 
UUCP:	decvax!harpo!seismo!rlgvax!cvl!elsie!mark
Phone:	(301) 496-5688



More information about the Comp.lang.c mailing list