aptr = malloc(nrows * ncols * sizeof(int));
rowptr = malloc(nrows * sizeof(int *));
What is the different with have no * inside sizeof(), eg sizeof(int), vs sizeof(int *)?
sizeof(int*)
returns the size of a pointer, while sizeof(int)
returns the size of an integer -- the two are NOT the same. And the lines you quoted are not the same either. Example: assume nrows = 10, ncols = 5 and sizeof(int) = 4. The first equation is 10 * 5 * 4 = 10 * 20 = 200. The second equation assume sizeof(int*) = 4, then 10 * 4 = 40. Clearly the two equations do not result in the same value.
Another way to look at those two code snippets you posted: the first allocates memory for a two dimensional array of integers while the second allocates memory for a one dimensional array of pointers.
perhaps look at this one as well.
#include <stdio.h>
int main()
{
int a[10];
int *a1;
printf("%d\n", sizeof(a));
printf("%d\n", sizeof(a1));
getchar();
return 0;
}
/* my output
40
4
*/
Ancient Dragon, sizeof(int *) and sizeof(int) just gives 4 bytes. That makes size since all memory location are 4byte long, well on 32 but machine. Am i right?
ssharish
>Ancient Dragon, sizeof(int *) and sizeof(int) just gives 4 bytes.
On your machine.
>That makes size since all memory location are 4byte long, well on 32 but machine.
That's certainly a logical assumption.
>Am i right?
No, you're not. A pointer in C doesn't apply to any specific implementation, it applies to an abstract machine where a pointer holds an address and the address specifies the location of an object. The value of an address is completely implementation-dependent to allow for such atrocities as segmented address spaces.
>The value of an address is completely implementation-dependent to allow for such atrocities as segmented address spaces.
So you mean to say that size of the int * could vary. Thats changes from machine to machine.
And can i also say that it would normally depend on how bit machine its like 32 or 64?
ssharish
>So you mean to say that size of the int * could vary.
>Thats changes from machine to machine.
Bingo.
>And can i also say that it would normally depend on how bit machine its like 32 or 64?
Assuming when you say 32-bit machine, you mean a machine that has a 32-bit address bus, then yes, it makes perfect sense for the size of a pointer (which holds an address) to be tied in some way to the addressable memory on the machine. That doesn't mean it'll be exactly the same though. For example, the 20-bit address bus on old x86 machines had a 32-bit far pointer and a 16-bit near pointer.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.