ive easily used new & delete in c++, but in c im getting confused
Code:
int size = 1;
int *arr = (int*)malloc(size*sizeof(int));
a dynamic int array that fits only 1 number its size = 0?
0 * anything = zero so don't use this in malloc?
i've seen code with simply
Code:
int *arr = (int*)malloc(size);
i assume this is incorrect because it also needs the size of the struct/etc?
here is a simple example I wrote:
Code:
int main(){
int size = 10;
int i=0;
char *arr = (char*)malloc(size*sizeof(char));
for(;i<size;i++)
arr[i] = (rand() % ('Z' - 'A'))+'A';
arr[size] = '\0';
printf("%s",arr);
free(arr);
getchar();getchar();getchar();
return 0;
}
why does this program crash when i add: free(arr); ?
when i change arr[size] = '\0'; to arr[size-1] = '\0'; it works
Code:
int main(){
int size = 1;
int i = 0;
int *arr;
int *temp;
arr = (int*)malloc(size*sizeof(int));
for(;i<size;i++){
arr[i] = rand() % 256;
printf("%d. %d",i,arr[i]);
}
++size;
temp = (int*)malloc(size*sizeof(int));
for(i=0;i<size-1;i++){
temp[i] = arr[i];
}
temp[size-1] = rand() % 256;
free(arr);
for(i=0;i<size;i++){
printf("\n%d. %d",i,temp[i]);
}
free(temp);
getchar();
return 0;
}
do all dynamic arrays (int,structs,etc) hold an empty cell at the end?