Im a very new to C language. Im trying to learn about to memory allocation with the next examples.
If I allocate memory for a integer like this:
int* pint = (int*)malloc(sizeof(int));
if (pint == NULL) {
printf("NULL pointer!");
} else {
*pint = 5;
printf("el valor es: %d", *pint);
free(pint);
}
This show perfectly the number 5 and the memory is liberated correctly
But If I try to do the same with a string like this:
char* string = (char*)malloc(sizeof(char)+1);
if (string == NULL) {
printf("NULL pointer!");
} else {
*string = "Hello World!";
printf("%s", *string);
free(string);
}
Why is that happening and how I can fix it?
thanks in advance
EDIT
Sorry I forgot to show the error that c compiler throws, my bad.
The error is:
warning: assignment to 'char' from 'char *' makes pointer from integer without a cast [-Wint-conversion]
Sorry for my bad english, it isn't my native language. Thanks again.
*string = "Hello World!";is not how you do it. See:strcpy().*dereferencing.int*is a trivial copy, andchar*would work, if you were copying a singlechar.*stringreturns the firstcharofstring, butprintfneeds achar *for%s. So, you want:printf("%s",string);But, yourmalloconly allocates space for one byte--not enough space for a string which needs space for the EOS (0x00) terminator. The TL;DR is: forego themallocand change*string = "Hello World!"-->string = strdup("Hello World!");strdup. But, the code you'll need is something akin to it. Here's a simple example:char * strdup(const char *str) { size_t len = strlen(str) + 1; char *dup = malloc(len); if (dup != NULL) memcpy(dup,str,len); return dup; }