Compatible, yes, the same thing, no.
Here is a good example of why they are not the same:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char fixedSizePtr[10];
char *dynamicSizePtr;
dynamicSizePtr = (char *)malloc(sizeof(char) * 10);
if(dynamicSizePtr == NULL) {
perror("Cannot malloc dynamicSizePtr");
return 1;
}
/* If you uncomment this portion, you will get a compiler error, because
a C string (char []) pointer that is given a fixed size cannot be modified
fixedSizePtr = (char *)malloc(sizeof(char) * 10);
if(fixedSizePtr == NULL) {
perror("Cannot malloc fixedSizePtr");
return 1;
}
*/
strncpy(dynamicSizePtr, "Bacon!", 10);
strncpy(fixedSizePtr, "Cheese!", 10);
printf("fixedSizePtr contains '%s' and is %d bytes in size\n",
fixedSizePtr, sizeof(fixedSizePtr));
printf("dynamicSizePtr contains '%s' and is %d bytes in size\n",
dynamicSizePtr, sizeof(dynamicSizePtr));
free(dynamicSizePtr);
return 0;
}
When run as is, it will return:
Quote:
~> ./test
fixedSizePtr contains 'Cheese!' and is 8 bytes in size
dynamicSizePtr contains 'Bacon!' and is 4 bytes in size
|
Notice, too, the size difference between the two? dynamicSizePtr was actually 10 characters long, but the sizeof returned 4.. because sizeof is returning the actual byte count of memory reserved for the variable, and in the case of dynamicSizePtr, it is only a memory location.
I don't know the specific terms for the differences, but this example shows one way they are different. They can be interchanged in a few different ways, however.