Yes, it's a matter of style, because you'd expect sizeof(char) to always be one.
On the other hand, it's very much an idiom to use sizeof(foo) when doing a malloc, and most importantly it makes the code self documenting.
Also better for maintenance, perhaps. If you were switching from char to wchar, you'd switch to
Copywchar *p = malloc( sizeof(wchar) * ( len + 1 ) );
without much thought. Whereas converting the statement char *p = malloc( len + 1 ); would require more thought. It's all about reducing mental overhead.
And as @Nyan suggests in a comment, you could also do
Copytype *p = malloc( sizeof(*p) * ( len + 1 ) );
for zero-terminated strings and
Copytype *p = malloc( sizeof(*p) * len ) );
for ordinary buffers.
Answer from brainjam on Stack Overflow[C] Storing strings using an array of char pointers and malloc.
How to allocate array of pointers for strings by malloc in C? - Stack Overflow
c - When to use malloc for char pointers - Stack Overflow
c - Initialize an array of char pointers with malloc - Stack Overflow
Videos
Yes, it's a matter of style, because you'd expect sizeof(char) to always be one.
On the other hand, it's very much an idiom to use sizeof(foo) when doing a malloc, and most importantly it makes the code self documenting.
Also better for maintenance, perhaps. If you were switching from char to wchar, you'd switch to
Copywchar *p = malloc( sizeof(wchar) * ( len + 1 ) );
without much thought. Whereas converting the statement char *p = malloc( len + 1 ); would require more thought. It's all about reducing mental overhead.
And as @Nyan suggests in a comment, you could also do
Copytype *p = malloc( sizeof(*p) * ( len + 1 ) );
for zero-terminated strings and
Copytype *p = malloc( sizeof(*p) * len ) );
for ordinary buffers.
It serves to self-document the operation. The language defines a char to be exactly one byte. It doesn't specify how many bits are in that byte as some machines have 8, 12, 16, 19, or 30 bit minimum addressable units (or more). But a char is always one byte.
I've been given the task of reading words into an array and then running insertion sort on them. The way it has been set out to do this is by using an array of char pointers and then assigning memory to each index in order to store a string. The code for that is already in place. But I just don't understand how using malloc makes space for a sting within a char? I'm honestly not even sure if what I just wrote makes sense. Pointers are frying my brain. Any help would be much appreciated. I've done a fair bit of Java before if that helps any explaination .
As I can understand from your assignment statement in while loop I think you need array of strings instead:
char** new_array;
new_array = malloc(30 * sizeof(char*)); // ignore casting malloc
Note: By doing = in while loop as below:
new_array [i] = new_message->array_pointers_of_strings [i];
you are just assigning address of string (its not deep copy), but because you are also writing "only address of strings" so I think this is what you wants.
Edit: waring "assignment discards qualifiers from pointer target type"
you are getting this warning because you are assigning a const char* to char* that would violate the rules of const-correctness.
You should declare your new_array like:
const char** new_array;
or remove const in declaration of 'array_pointers_of_strings' from message stricture.
This:
char** p = malloc(30 * sizeof(char*));
will allocate a buffer big enough to hold 30 pointers to char (or string pointers, if you will) and assign to p its address.
p[0] is pointer 0, p[1] is pointer 1, ..., p[29] is pointer 29.
Old answer...
If I understand the question correctly, you can either create a fixed number of them by simply declaring variables of the type message:
message msg1, msg2, ...;
or you can allocate them dynamically:
message *pmsg1 = malloc(sizeof(message)), *pmsg2 = malloc(sizeof(message)), ...;
As was indicated by others, you don't need to use malloc just to do:
const char *foo = "bar";
The reason for that is exactly that *foo is a pointer — when you initialize foo you're not creating a copy of the string, just a pointer to where "bar" lives in the data section of your executable. You can copy that pointer as often as you'd like, but remember, they're always pointing back to the same single instance of that string.
So when should you use malloc? Normally you use strdup() to copy a string, which handles the malloc in the background. e.g.
const char *foo = "bar";
char *bar = strdup(foo); /* now contains a new copy of "bar" */
printf("%s\n", bar); /* prints "bar" */
free(bar); /* frees memory created by strdup */
Now, we finally get around to a case where you may want to malloc if you're using sprintf() or, more safely snprintf() which creates / formats a new string.
char *foo = malloc(sizeof(char) * 1024); /* buffer for 1024 chars */
snprintf(foo, 1024, "%s - %s\n", "foo", "bar"); /* puts "foo - bar\n" in foo */
printf(foo); /* prints "foo - bar" */
free(foo); /* frees mem from malloc */
malloc is for allocating memory on the free-store. If you have a string literal that you do not want to modify the following is ok:
char *literal = "foo";
However, if you want to be able to modify it, use it as a buffer to hold a line of input and so on, use malloc:
char *buf = (char*) malloc(BUFSIZE); /* define BUFSIZE before */
// ...
free(buf);
char *array[10] declares an array of 10 pointers to char. It is not necessary to malloc storage for this array; it is embedded in struct List. Thus, the first call to malloc is unnecessary, as is the check immediately afterward.
The call to malloc inside the loop, and check after, are correct.
Also, in C, do not cast the return value of malloc; it can actually hide bugs.
Also also, sizeof(char) is 1 by definition and therefore you should never write it.
struct List
{
char *array[10];
};
int
main(void)
{
struct List input;
for (int i = 0; i < 10; i++)
{
input.array[i] = malloc(10);
if (!input.array[i])
return EXIT_FAILURE;
}
/* presumably more code here */
return 0;
}
malloc(10 * sizeof(char*));
you have to allocate 10 char pointers (4 byte / 8byte) and not 10 chars (1 byte)
//Edit: I ignored the struct. first malloc isn't necessary. See the other answer.
Hello,
I am just brushing up on pointers in preparation for a C unit I will be doing.
For this script
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char (* ptr)[10] = malloc(sizeof(char) * 10);
for(int i = 0; i < 8; i++) {
(*ptr)[i] = 'h';
}
*ptr[9] = '\0';
//free(ptr); //-------------THIS LINE
printf("%s\n",*ptr);
return 0;
}What is the difference between 1. free(*ptr) and 2.free(ptr)?
2. Frees the ARRAY that ptr is pointing to
-
Frees the first element in the array
Is there any difference?
By the way I know that "printf("%s\n",*ptr);" accesses an invalid pointer.
I just used it to notice the printed strings is different whether I free 1 or 2.
Thanks