Emuforums.com

Go Back   Emuforums.com > General Discussion > Web development / Programming
About Us Register FAQ Members List Calendar Mark Forums Read

Reply
 
LinkBack Thread Tools Display Modes
Old September 25th, 2003   #1 (permalink)
General of Tangerines
 
RZetlin's Avatar
 
Join Date: Jun 2001
Location: Defending the Sea
Posts: 3,885
Post C: Initializing an array using malloc

In C Programming, if want to initialize an fixed array in C I would write this:

char array[10]={NULL};

With malloc I would create an array like this

char *array;
int size;
array=(*char)malloc (size);

Is there a short way to initialize the an malloc array without using a for loop?
__________________


AMD Athlon 64 3700+ | 2 GB RAM | XFX Nvidia 6800 GS 256 MB XXX Edition | Win XP Pro SP2
RZetlin is offline   Reply With Quote
Old September 25th, 2003   #2 (permalink)
Ramsus K
 
Join Date: Mar 2003
Location: Oklahoma
Posts: 461
Re: C: Initializing an array using malloc

You could just write:

char array[10] = {0};

Since NULL is just 0 whereever pointers are concerned.

Anyway, instead of using malloc, just use calloc. calloc works like malloc, but returns "zeroed" memory.

void *calloc(size_t nmemb, size_t size);
void *malloc(size_t size);

calloc() allocates memory for an array of nmemb elements of size bytes each and returns a pointer to the allocated memory. The memory is set to zero.

malloc() allocates size bytes and returns a pointer to the allocated memory. The memory is not cleared.

So:

Code:
char *s = 0; 
size_t len = 50;
if (!(s = calloc(len, sizeof(char))))
    return 0; /* memory allocation failed */

Last edited by RamsusX; September 25th, 2003 at 01:44.
RamsusX is offline   Reply With Quote
Old September 25th, 2003   #3 (permalink)
/dev/user
 
Ipswitch's Avatar
 
Join Date: Nov 2002
Location: Internet
Posts: 407
Re: C: Initializing an array using malloc

if you have an array already, you could memcpy your data into the new one, but otherwise you really cant put your own arbitrary data into an array without a for loop.
Ipswitch is offline   Reply With Quote
Old September 25th, 2003   #4 (permalink)
Ramsus K
 
Join Date: Mar 2003
Location: Oklahoma
Posts: 461
Re: C: Initializing an array using malloc

Ah yes, if you also want to initialize your allocated memory to something other than 0, then you need to use a for loop. There's no way around it.

You can create pointers to string literals like so:
char *s = "This is a string literal.";
But you can't change string literals, so that's fairly useless.
RamsusX is offline   Reply With Quote
Old September 25th, 2003   #5 (permalink)
Registered User
 
Join Date: Sep 2001
Posts: 47
Re: C: Initializing an array using malloc

theres no way to dynamically allocate and initialise an Array in one go.
Edit: ermmm, except calloc which returns zeroed Memory *cough* *cough*

First you have to allocate the Memory required:
char *array = malloc( size * sizeof(char));

Then you can use memset to set a region of bytes to a certain value.
memset( array, 'X', size ); // sets the whole array to XXX....
N-Rage is offline   Reply With Quote
Old September 26th, 2003   #6 (permalink)
Emu author
 
Join Date: Apr 2001
Location: Bloomington IN, USA
Posts: 1,061
Re: C: Initializing an array using malloc

It should be pointed out that NULL is NOT in fact guaranteed to be zero (this is not specified in any of the ANSI C standards, as far as I'm aware, and I've heard of systems with non-zero NULL). Compilers that allow you to set pointers to zero without warning (cough, MSVC, cough) or even worse, ues NULL as integer 0, are incorrect.

And..
char array[10] = { NULL };
is meaningless by this virtue, since you're setting only the first entry of the array, a character, to a pointer (NULL). In this case 0 WOULD be more appropriate, although I can't fathom why you'd only want to set the first value. This would NOT set all 10 values, and could land you a warning (maybe even an error, not sure because I've never tried anything strange like that)

Unfortunately, the useful initialization constructs really only do exist as initializers, which is too bad since they'd be useful in other situations. There are probably more guarantees in initializations that you can't promise for later periods in its life.

BTW, calloc is deemed bad to use now for some reason. I'm not exactly sure why, but there's probably a good reason. Most people just use malloc/memset these days.

EDIT: I'm 90% asleep right now so I've been making a lot of strange typos.. using words for other words.. :\

- Exo
Exophase is offline   Reply With Quote
Old September 26th, 2003   #7 (permalink)
Ramsus K
 
Join Date: Mar 2003
Location: Oklahoma
Posts: 461
Re: C: Initializing an array using malloc

Quote:
Originally Posted by Exophase
It should be pointed out that NULL is NOT in fact guaranteed to be zero (this is not specified in any of the ANSI C standards, as far as I'm aware, and I've heard of systems with non-zero NULL). Compilers that allow you to set pointers to zero without warning (cough, MSVC, cough) or even worse, ues NULL as integer 0, are incorrect.
In the context of a pointer, the C compiler recognizes 0 as representing a NULL value. This means that 0 isn't literally interpretted as the memory address 0 but as NULL. This also means that in C, NULL and 0 are equivalent. In fact, NULL is a macro for (char *)0 (the typecast forces 0 to be in the context of a pointer).

Quote:
And..
char array[10] = { NULL };
is meaningless by this virtue, since you're setting only the first entry of the array, a character, to a pointer (NULL). In this case 0 WOULD be more appropriate, although I can't fathom why you'd only want to set the first value. This would NOT set all 10 values, and could land you a warning (maybe even an error, not sure because I've never tried anything strange like that)
When you initialize an array to a list {} containing fewer elements than the array holds, then every remaining element is zero-initialized. That's why {0} works.
RamsusX is offline   Reply With Quote
Old September 27th, 2003   #8 (permalink)
/dev/user
 
Ipswitch's Avatar
 
Join Date: Nov 2002
Location: Internet
Posts: 407
Re: C: Initializing an array using malloc

i thought the
char array[10] = { blah )
was a borland compiler special
Ipswitch is offline   Reply With Quote
Old September 27th, 2003   #9 (permalink)
Emu author
 
Join Date: Apr 2001
Location: Bloomington IN, USA
Posts: 1,061
Re: C: Initializing an array using malloc

In the context of a pointer, the C compiler recognizes 0 as representing a NULL value. This means that 0 isn't literally interpretted as the memory address 0 but as NULL. This also means that in C, NULL and 0 are equivalent. In fact, NULL is a macro for (char *)0 (the typecast forces 0 to be in the context of a pointer).

I'm pretty sure that that it's not standardized like that. If it is, then it's pretty poor form on C's part, IMO.. but I've read hazard cautions against using 0 because it's platform dependant.

When you initialize an array to a list {} containing fewer elements than the array holds, then every remaining element is zero-initialized. That's why {0} works.

I've never done that before, it sounds pretty obscure. All this just to get an array set to NULL, when it was a bunch of chars anyway... ^_^

- Exo
Exophase is offline   Reply With Quote
Old September 27th, 2003   #10 (permalink)
Ramsus K
 
Join Date: Mar 2003
Location: Oklahoma
Posts: 461
Re: C: Initializing an array using malloc

Quote:
Originally Posted by Exophase
In the context of a pointer, the C compiler recognizes 0 as representing a NULL value. This means that 0 isn't literally interpretted as the memory address 0 but as NULL. This also means that in C, NULL and 0 are equivalent. In fact, NULL is a macro for (char *)0 (the typecast forces 0 to be in the context of a pointer).

I'm pretty sure that that it's not standardized like that. If it is, then it's pretty poor form on C's part, IMO.. but I've read hazard cautions against using 0 because it's platform dependant.
From K&R's The C Programming Language:
Quote:
Pointers and integers are not interchangeable. Zero is the sole exception: the constant zero may be assigned to a pointer, and a pointer may be compared with the constant zero. The symbolic constant NULL is often used in place of zero, as a mnemonic to indicate more clearly that this is a special value for a pointer. NULL is defined in <stdio.h>.
See the Comp.lang.c FAQ: http://www.eskimo.com/~scs/C-faq/q5.2.html

The constant 0 IS the C representation of a null pointer, not the memory address 0. This is something the compiler resolves when compiling the code. It is part of the language specification. It is standard and portable.

Only when passed to a function without a prototype in the current scope or with variable size arguments (e.g. printf) is it interpreted as the integer 0, in which case you should typecast it. This is because the compiler can't tell what the type the argument should be so 0 means integer 0 and not a null pointer in this context. As such, integer 0 means the memory address 0, which is not a null pointer (or isn't guaranteed to be).

Because of this, the NULL macro is also part of the C language. This is just 0 typecast to (char *) ((void *) in ANSI I believe) to ensure that NULL is always the constant 0 in the context of a pointer, which is interpreted by the compiler as meaning the null pointer IN ALL CASES.


Also:
Code:
char *p;
int i=0;
p = i;
I wouldn't trust p to be a null pointer now since it was assigned to the integer value 0, not the constant 0.

If i were a pointer that was initialized to the constant 0, then i would've been null. Then assigning p to i would've resulted in p being a null pointer.


If you know what you're doing, then using the constant 0 instead of the NULL macro everywhere is no big deal.

Quote:
When you initialize an array to a list {} containing fewer elements than the array holds, then every remaining element is zero-initialized. That's why {0} works.

I've never done that before, it sounds pretty obscure. All this just to get an array set to NULL, when it was a bunch of chars anyway... ^_^

- Exo
It's mostly used to initialize an array of structures so that all of the fields of every member of the array is initialized to 0 or a null pointer, which can be useful in some cases. Some people also just dislike not initializing variables.

Also, it just sets the value of every member of the array of char to 0 (not the array to NULL). If you just want an empty string, it's easier to set the first character of the array to '\0'.

Last edited by RamsusX; September 27th, 2003 at 03:16.
RamsusX is offline   Reply With Quote
Old September 27th, 2003   #11 (permalink)
Emu author
 
Join Date: Apr 2001
Location: Bloomington IN, USA
Posts: 1,061
Re: C: Initializing an array using malloc

I stand corrected, you are indeed right about (char *)0 being portable. I prefer NULL for clarity, though (also, I'd imagine setting a pointer to 0 could at least give a warning, since the 0 is still an integer type in this form... so the cast would at least be helpful).

- Exo
Exophase is offline   Reply With Quote
Old September 27th, 2003   #12 (permalink)
Ramsus K
 
Join Date: Mar 2003
Location: Oklahoma
Posts: 461
Re: C: Initializing an array using malloc

Quote:
Originally Posted by Exophase
I stand corrected, you are indeed right about (char *)0 being portable. I prefer NULL for clarity, though (also, I'd imagine setting a pointer to 0 could at least give a warning, since the 0 is still an integer type in this form... so the cast would at least be helpful).

- Exo
But with:
Code:
void Test(void *p) 
{
  if(!p) {
    printf("Argument is a null pointer.\n");
  }
}

int main()
{
  char *p = 0;
  char *s;
  s = 0;
  s = p;
  p = s;
  Test(0);
  return 0;
}
0 is in the context of a pointer and is a null pointer value in all of these cases (except return of course). There is no need for a warning because 0 here is the null pointer, not an integer 0.

There are only a two occasions where the constant 0 needs to be typecast: when you're using a function that hasn't been declared within the scope of your function call, and when you're using a function that uses a variable size argument list. Both of these aren't very common.
RamsusX is offline   Reply With Quote
Old September 27th, 2003   #13 (permalink)
Emu author
 
Join Date: Apr 2001
Location: Bloomington IN, USA
Posts: 1,061
Re: C: Initializing an array using malloc

I understand that.. I just don't think it's really that appropriate for something like "0" to be context sensitive without casting. C has some pretty crazy things ;P

- Exo
Exophase is offline   Reply With Quote
Old September 27th, 2003   #14 (permalink)
Ramsus K
 
Join Date: Mar 2003
Location: Oklahoma
Posts: 461
Re: C: Initializing an array using malloc

It makes life more interesting.
RamsusX is offline   Reply With Quote
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


All times are GMT. The time now is 21:32.

© 2006 - 2008 Emu Forums | About Emu Forums | Legal | A member of the Crowdgather Forum Community


Powered by vBulletin® Version 3.7.0 Release Candidate 3
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
SEO by vBSEO 3.2.0 RC5