Hi,
I'm trying to use a dynamic array but for some reason it won't work. This is
my code :
int *test;
int numElements = 2;
test = (int *) malloc (numElements * sizeof(int));
if (test= NULL) printf("Can't allocate\n"); // Nothing happens here
so it's ok I guess
test[0] = 10; // <- CRASH!
printf( "test= %d\n",test[0] );
I copied it from the internet and it seems that they all do it this way?
Then why won't this work? My computer sure has enough for 2 integers...
Greetings,
Rick
Nov 13 '05
20 12784
"Rick" <as******@hotma il.com> wrote: Ok, ok, I quickly typed it over. ( s = NULL ) is stupid indeed but in the real code there are really 2 == :) And no, although there's a bug it does compile. But look, an exact copy now :
int *da; int numElements = 2;
da = (int *) malloc (numElements * sizeof(int)); if (da== NULL) printf("damn\n" ); da[0] = 10; // The same problem printf( "test= %d\n",da[0] );
Sorry, but your code confuses my compiler:
4: conflicting types for `da'
1: previous declaration of `da'
4: warning: implicit declaration of function `malloc'
4: warning: initialization makes integer from pointer without a cast
4: initializer element is not constant
4: warning: data definition has no type or storage class
5: parse error before "if"
6: warning: type defaults to `int' in declaration of `da'
6: conflicting types for `da'
4: previous declaration of `da'
6: invalid initializer
6: warning: data definition has no type or storage class
7: parse error before string constant
7: warning: type defaults to `int' in declaration of `printf'
7: warning: conflicting types for built-in function `printf'
7: warning: data definition has no type or storage class
Please post a compilable version of your code.
Regards
--
Irrwahn
(ir*******@free net.de)
Strange you compiler doesn't take it. Well, maybe it's because of my very
old Borland version. But it's fixed now, the only thing I forgot the whole
time was including stdlib :)
Greetings,
Rick
"Rick" <as******@hotma il.com> wrote: Wait! I talk too fast. It does work now, after including #include <stdlib.h> as well. Are their more versions of malloc or something? The compiler didn't say anything.
You just dicovered the reasons why it's usually bad practice to cast the
return value of malloc (it may hide the fact that you forgot to include
stdlib.h), and why it's good practice to turn up the warning level of
your compiler to maxinmum and treat warnings as errors.
Regards
--
Irrwahn
(ir*******@free net.de)
"Rick" <as******@hotma il.com> wrote: Strange you compiler doesn't take it. Well, maybe it's because of my very old Borland version. But it's fixed now, the only thing I forgot the whole time was including stdlib :)
Plus including stdio.h, plus wrapping your code in a main function, plus
casting the return value of malloc, plus failing to pump up your
compilers warning level.
Regards
--
Irrwahn
(ir*******@free net.de)
Do you have magic powers? How do you know I forgot all that stuff? I only
gave a piece of the code, not the complete thing. Anyway, everybody thanks
for helping!
Greetings,
Rick
"Rick" <as******@hotma il.com> wrote: Do you have magic powers?
Not yet, but I've got an ACME Crystal Ball [TM]. ;-)
How do you know I forgot all that stuff? I only gave a piece of the code, not the complete thing.
That was the main (sic) problem.
Anyway, everybody thanks for helping!
You're welcome.
Regards
--
Irrwahn
(ir*******@free net.de)
In <3f************ ***********@new s.xs4all.nl> "Rick" <as******@hotma il.com> writes: Wait! I talk too fast. It does work now, after including #include <stdlib.h> as well. Are their more versions of malloc or something? The compiler didn't say anything.
You shot yourself in the foot, by casting the malloc call. Without the
cast, the compiler MUST emit a diagnostic, if you don't include <stdlib.h>
because malloc is implicitly declared as returning int, but used in a
pointer context.
The first rule of computer programming: know what you're doing.
The second rule of computer programming: know how to use your tools.
Actually, these rules apply to any human activity...
Compile these two programs and note the difference:
int main()
{
char *p = malloc(10);
return 0;
}
and
int main()
{
char *p = (char *)malloc(10);
return 0;
}
They're both equally broken (due to the lack of declaration for malloc),
but only the first one requires a diagnostic from the compiler.
The next exercise is to find out how to use your compiler so that even
the second program generates a diagnostic, because you're using a function
without declaring it. C89 allows this, but it is such an atrocious idea
that practically all compilers can warn about it, if you raise their
warning level high enough. You really don't want to use undeclared
functions in your programs and, if you have to declare them yourself,
make sure you use prototype declarations.
If the compiler can find your bugs, it is downright idiotic not to let it
do it for you.
Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Rick wrote: Do you have magic powers? How do you know I forgot all that stuff? I only gave a piece of the code, not the complete thing. Anyway, everybody thanks for helping!
Please quote a relevant portion of the post you are replying to.
Brian Rodenborn
On Wed, 29 Oct 2003 14:31:41 +0100, in comp.lang.c , "Rick"
<as******@hotma il.com> wrote: Wait! I talk too fast. It does work now, after including #include <stdlib.h> as well. Are their more versions of malloc or something? The compiler didn't say anything.
Rick, sorry about this, but I'm going to store your post for
perpetuity, as it a classic example of someone actually getting bitten
by the reason for NOT casting malloc.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.c om/ms3/bchambless0/welcome_to_clc. html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
On Wed, 29 Oct 2003 14:31:41 +0100, in comp.lang.c , "Rick"
<as******@hotma il.com> wrote: Wait! I talk too fast. It does work now, after including #include <stdlib.h> as well. Are their more versions of malloc or something?
There's only one version ,declared in stdlib.h.
The compiler didn't say anything.
Its not required to. Your cast silenced the only warning it could have
made, "implicit conversion from int to pointer". In the absence of a
proper prototype for a function, the compiler assumes that it returns
an int. DONT cast malloc in C code, for this very reason.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.c om/ms3/bchambless0/welcome_to_clc. html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =--- This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: meyousikmann |
last post by:
The following code just sets up and fills a dynamic array of integers.
#include <cstdlib>
int main()
{
int* intArray = NULL;
int count;
count = 20;
|
by: Scott Lyons |
last post by:
Hey all,
Can someone help me figure out how to pass a dynamic array into a function?
Its been giving me some trouble, and my textbook of course doesnt cover the
issue. Its probably something simple, but its just not popping into my mind
at the moment.
My little snippet of code is below. Basically, the studentID array is
dynamic so it will fit any length of a Student's Name. What I'm trying to
do is place this chunk of code into a...
|
by: genc ymeri |
last post by:
Hi,
What can I use in C# for dynamic arrays ???? I have some records (struts in
..Net) and want to store them in a dynamic "arrays" or object list.
I noticed the in C# arrays' length can't be extented in run time. So, what
should I use ?
Thank You in advance.
PS:
|
by: Peter Olcott |
last post by:
I need to know how to get the solution mentioned below to work. The
solution is from gbayles Jan 29 2001, 12:50 pm, link is provided below:
> http://groups.google.com/group/comp.lang.c++/msg/db577c43260a5310?hl
>
>Another way is to create a one dimensional array and handle the
>indexing yourself (index = row * row_size + col). This is readily
>implemented in template classes that can create dynamically allocated
>multi-dimensional...
|
by: learnfpga |
last post by:
Here is a little code I wrote to add the numbers input by the
user.....I was wondering if its possible to have the same functionality
without using dynamic arrays.....just curious.....
//trying to get input from the user to add all the numbers that user
inputs
//tried to do it without dynamic memory usage but probably cannot
achieve it
//here is using "new" and "delete" operator....
| |
by: assgar |
last post by:
Hi
Developemnt on win2003 server. Final server will be linux
Apache,Mysql and PHP is being used.
I use 2 scripts(form and process).
The form displays multiple dynamic rows with chechboxs, input box for units of service, description of the service and each row has its own dropdown list of unit fees that apply.
Each dynamically created row will return 3 values fee1_choice, fee1_unit and fee1_money.
Note The above informaton is...
|
by: hobbes992 |
last post by:
Howdy folks,
I've been working on a c project, compiling using gcc, and I've reached a problem. The assignment requires creation of a two-level directory file system. No files have to be added or deleted, however it must be initialized by a function during run-time to contain so many users which each contain so many directories of which each contain so many files. I've completed the program and have it running flawlessly without implementing...
|
by: KioKrofov |
last post by:
Hello,
I am trying to find out how Dynamic Arrays are actually stored in memory. Really, I want to know how Vectors are stored in memory, but I deduce they are stored the same way.
If you have a dynamic array initialized at size 50, and it then needs to increase to size 75, what happens?
Does element 49 contain some sort of pointer to the next 25 elements, or are a new 75 consecutive spots in memory allocated, and then the first 50...
|
by: headware |
last post by:
Do dynamic arrays declared using ReDim have to be freed? I assume that
if it's an array of dynamically created objects (e.g.
Scripting.Dictionary), each one of those objects will have to be set
to Nothing in a for loop, but what about the array itself? Or what if
the array is dynamic but it just consists of integers or strings, not
dynamically allocated objects? Does it have to be set to Nothing?
Thanks,
Dave
|
by: Sunny |
last post by:
Hi,
Is there a way in javascript to create Dynamic arrays or arrays on
fly.
Something Like:
var "ptsgN"+sd = new Array();
Here sd is incrementing by 1.
I have lots of data that I am putting in arrays.
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |