473,695 Members | 2,568 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dynamic arrays

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 #1
20 12767
Rick wrote:
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

^
Hur, hur!

You want ==.

Jirka

Nov 13 '05 #2
"Rick" <as******@hotma il.com> wrote:
Hi,

I'm trying to use a dynamic array but for some reason it won't work. This is
my code :
It's certainly not, it won't even compile.

#include <stdio.h>
#include <stdlib.h>

int main(void)
{ int *test;
int numElements = 2;

test = (int *) malloc (numElements * sizeof(int)); ^ spurious cast, you'd better write:

test = malloc ( numElements * sizeof *test );
if (test= NULL) printf("Can't allocate\n"); // Nothing happens here ^ you assign NULL to test here
so it's ok I guess No, you want:

if ( test == NULL )
{
printf("Can't allocate\n");
return EXIT_FAILURE;
}
test[0] = 10; // <- CRASH!
It's not surprising for NULL[0] = 10; to crash. You invoked undefined
behaviour.
printf( "test= %d\n",test[0] );
return EXIT_SUCCESS;
}
I copied it from the internet and it seems that they all do it this way? No, fortunately not.
Then why won't this work? My computer sure has enough for 2 integers...

See above.

HTH
Regards
--
Irrwahn
(ir*******@free net.de)
Nov 13 '05 #3
Jirka Klaue wrote:
Rick wrote:
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


^
Hur, hur!

You want ==.


To OP.
That's why many programmers prefer to write:
if (NULL==test) {
/* ... */
}
To catch the error at compile time.

e.j.s.

--
The white zone is for loading and unloading only.
(Frank Zappa)

Nov 13 '05 #4
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] );

Also tried without the == null line, just for sure, but it doesn't work
neither. I also tried it without (int *)but it keeps crashing.

Greetings,
Rick
Nov 13 '05 #5


Rick 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] );

Also tried without the == null line, just for sure, but it doesn't work
neither. I also tried it without (int *)but it keeps crashing.


You have a flaw. You should not simply print a message
if the allocation failed and then continue on as if it was
successful. You need and if-else or an exit.

Try this and see if this crashes:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
int *da;
int numElements = 2;

da = malloc(numEleme nts * sizeof(int));
if (da == NULL) printf("damn\n" );
else
{
da[0] = 10;
printf( "test= %d\n",da[0] );
free(da);
}
return 0;
}

--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapi dsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 13 '05 #6
Very True, but it doesn't solve the problem...

Greetings,
Rick
Nov 13 '05 #7
"sellountos euripides" <se********@mec h.upatras.gr> wrote in message
news:bn******** **@nic.grnet.gr ...
if (test= NULL) printf("Can't allocate\n");

^
Hur, hur!

You want ==.


To OP.
That's why many programmers prefer to write:
if (NULL==test) {
/* ... */
}
To catch the error at compile time.


I prefer to increase the warning level from my compiler, which also sets off
an alarm bell in this type of situation:

int i, j;
/* ... */
if (i = /* whoops! */ j) { /* ... */ }

Alex
Nov 13 '05 #8
Ow, Al, I tried you code (thanks for that) in the main but it still crashes.
What the heck is going on? Even my drunken brain can store 2 integers. It's
just a normal pc. Maybe it are some settings in the old Borland C++??

Greetings,
Rick
Nov 13 '05 #9
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.

Thanks!
Rick
Nov 13 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
4038
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;
4
7681
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...
3
2813
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:
60
10153
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...
4
2469
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....
2
7051
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...
4
5065
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...
1
2674
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...
2
2115
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
4
5424
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.
0
8585
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9132
Oralloy
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...
0
9004
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8864
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8838
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5842
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();...
0
4351
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...
0
4592
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2288
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.