473,785 Members | 2,789 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Variable length array confusion

Hai,
I studied that the array size is fixed. But I come across a word
called "variable length array". Is it possible to change the array
size? So I tried the following:
#include<stdio. h>
#include<stdlib .h>
int main(void)
{
int y[3] = { 7, 9,10},i;
for (;i<20;i++)
printf("%d\n",y[i]);
return 0;
}

This is a wrong one and given me a runtime error.

Then what is variable length array?

So I tried the following:

int main(void)
{
int y[3] = { 7, 9,10},i;
for (;i<20;i++)
{
*y = malloc(sizeof *y);
if(*y == NULL)
exit(EXIT_FAILU RE);
else
printf("%d size=%d\n",y[i],sizeof y);

}
return 0;
}

OUTPUT:

589600 size=12
9 size=12
10 size=12
0 size=12
0 size=12
0 size=12
588632 size=12
11912 size=12
1 size=12
589584 size=12
593160 size=12
....
....
.....

Even though it gave some warning and runtime error I can see the array
size has changed since I used malloc and allocated with 3 * 4 (C array
starts with zero) so the size = 12.

1)Is my understanding of the above is correct?

2)Is the above program behavior is undefined?

Kindly help.
Nov 13 '05 #1
5 14114

<da***********@ yahoo.com> schrieb im Newsbeitrag
news:a3******** *************** ***@posting.goo gle.com...
Hai,
I studied that the array size is fixed. But I come across a word
called "variable length array". Is it possible to change the array
size? So I tried the following:
#include<stdio. h>
#include<stdlib .h>
int main(void)
{
int y[3] = { 7, 9,10},i;
for (;i<20;i++)
printf("%d\n",y[i]);
return 0;
}

This is a wrong one and given me a runtime error.

Then what is variable length array?


Here is an example
(assuming you have no C99 compiler)

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

int main(void)
{
int i;
void *tmp;
int *y = malloc(20 * sizeof *y);

if(y)
{
y[0] = 7;
y[1] = 9;
y[2] = 10;
for(i = 3; i < 20; i++)
{
y[i] = 0;
}
for(i = 0; i < 20; i++)
{
printf("%d ", y[i]);
}
printf("\n");
tmp = realloc(y, 25 * sizeof *y);
if(tmp)
{
y = tmp;
for(i = 3; i < 25; i++)
{
y[i] = i;
}
for(i = 0; i < 25; i++)
{
printf("%d ", y[i]);
}
printf("\n");
}
free(y);
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}

Robert
Nov 13 '05 #2
da***********@y ahoo.com wrote:
I studied that the array size is fixed. But I come across a word
called "variable length array". Is it possible to change the array
size? So I tried the following:
#include<stdio. h>
#include<stdlib .h>
int main(void)
{
int y[3] = { 7, 9,10},i;
for (;i<20;i++)
You also need to initialize i, the way you use it here it will have
some completely random value. Only static and global variables are
initialized to 0.
printf("%d\n",y[i]);
return 0;
} This is a wrong one and given me a runtime error.
Yes, because you're trying to access non-existent elements of the array
'y'. Everything after y[2] does not belong to you.
Then what is variable length array? So I tried the following: int main(void)
{
int y[3] = { 7, 9,10},i;
for (;i<20;i++)
Again, you need to initialize i, use e.g.
for ( i = 0; i < 20; i++ )
{
*y = malloc(sizeof *y);
Here you allocate memory for a single integer and assign the address
you get back from malloc() to the first element of the array 'y',
thereby implicitely converting the address to an integer (note that
writing *y is the same as y[0] because y[i] is always the same as
*(y+i)). And, of course, that's nothing you should be doing and the
compiler should emit a warning, at least if you have raised the
warning level to something useful.
if(*y == NULL)
exit(EXIT_FAILU RE);
else
printf("%d size=%d\n",y[i],sizeof y);
Here you still run into the same problem as in your first program, you
read past the last element of the 'y' array. Just having allocated some
memory and assigned the address to the first element of the array doesn't
change anything. And 'sizeof y' will always be 12 because that's the
amount of memory taken by the array 'y' (you seem to run this on a
machine where siezof(int) is 4). You can't change the size of 'y' by
allocation, it's fixed the moment you compiled the program.
}
return 0;
}


There are two things you seem to be confusing, variable length arrays
and dynamically allocated arrays. Variable length arrays are a feature
that has been introduced in (standard) C only with the new C99 standard
and not all compilers support it yet. It means arrays of a length that
hasn't been compiled in as a fixed number into the program but is only
calculated during runtime. E.g. you can have a function like this

void vla( int n )
{
int x[ n ];
int i;

for ( i = 0; i < n; i++ )
x[ i ] = i;
}

This wasn't allowed with C89 (but some compilers did allow it as an
extension, e.g. gcc) and which only a C99 compliant compiler must
support.

On the other had you have dynamically allocated arrays:

void daa( int n )
{
int *x;
int i;

x = malloc( n * sizepf *x );
if ( x == NULL )
{
fprintf( stderr, "Can't allocate memory\n" );
exit( EXIT_FAILURE );
}

for ( i = 0; i < n; i++ )
x[ i ] = i;

free( x );
}

This is legal even with C89. Of course 'x' isn't a real array but just
a pointer to some memory that can hold the number of integers you need.
And in many places 'x' can be treated like a real array, but there are
subtle differences, e.g. sizeof x is not the amount of memory it's
pointing to but the size of a pointer. And, of course, you must free()
the memory you allocated when you don't need it anymore.

Regards, Jens
--
_ _____ _____
| ||_ _||_ _| Je***********@p hysik.fu-berlin.de
_ | | | | | |
| |_| | | | | | http://www.physik.fu-berlin.de/~toerring
\___/ens|_|homs|_|oe rring
Nov 13 '05 #3
On 29 Sep 2003 06:00:42 -0700, in comp.lang.c ,
da***********@y ahoo.com wrote:
Hai,
I studied that the array size is fixed. But I come across a word
called "variable length array".
A variable length array is one whose length is a variable !!

In old C, you had to declare variables with a constant as the length
double foo[56];

in new C you can declare them using a variable
int bar = 56;
double foo[bar];

This is obviously handy if bar were a parameter to some function that
needed a bar-sized array of doubles.
Is it possible to change the array
size?


Once you create it, its fixed. (Note that malloc doesn't create
arrays, although malloc'ed memory can be treated as an array to all
intents and purposes, which of course begs the question "whats the
point of VLAs then?")

--
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>
Nov 13 '05 #4
Je***********@p hysik.fu-berlin.de wrote in message news:<bl******* *****@uni-berlin.de>...
da***********@y ahoo.com wrote:
I studied that the array size is fixed. But I come across a word
called "variable length array". Is it possible to change the array
size? So I tried the following:
#include<stdio. h>
#include<stdlib .h>
int main(void)
{
int y[3] = { 7, 9,10},i;
for (;i<20;i++)
You also need to initialize i, the way you use it here it will have
some completely random value. Only static and global variables are
initialized to 0.
printf("%d\n",y[i]);
return 0;
}

This is a wrong one and given me a runtime error.


Yes, because you're trying to access non-existent elements of the array
'y'. Everything after y[2] does not belong to you.
Then what is variable length array?

So I tried the following:

int main(void)
{
int y[3] = { 7, 9,10},i;
for (;i<20;i++)


Again, you need to initialize i, use e.g.
for ( i = 0; i < 20; i++ )
{
*y = malloc(sizeof *y);


Here you allocate memory for a single integer and assign the address
you get back from malloc() to the first element of the array 'y',
thereby implicitely converting the address to an integer (note that
writing *y is the same as y[0] because y[i] is always the same as
*(y+i)). And, of course, that's nothing you should be doing and the
compiler should emit a warning, at least if you have raised the
warning level to something useful.

^^^^^^^^^^^^^^^

Yes , gcc Wall o temp temp.c
Gives me warning about the assignment.

if(*y == NULL)
exit(EXIT_FAILU RE);
else
printf("%d size=%d\n",y[i],sizeof y);
Here you still run into the same problem as in your first program, you
read past the last element of the 'y' array. Just having allocated some
memory and assigned the address to the first element of the array doesn't
change anything. And 'sizeof y' will always be 12 because that's the
amount of memory taken by the array 'y' (you seem to run this on a
machine where siezof(int) is 4). You can't change the size of 'y' by
allocation, it's fixed the moment you compiled the program.
}
return 0;
}


There are two things you seem to be confusing, variable length arrays
and dynamically allocated arrays. Variable length arrays are a feature
that has been introduced in (standard) C only with the new C99 standard
and not all compilers support it yet. It means arrays of a length that
hasn't been compiled in as a fixed number into the program but is only
calculated during runtime. E.g. you can have a function like this

void vla( int n )
{
int x[ n ];
int i;

for ( i = 0; i < n; i++ )
x[ i ] = i;
}

This wasn't allowed with C89 (but some compilers did allow it as an
extension, e.g. gcc) and which only a C99 compliant compiler must
support.

On the other had you have dynamically allocated arrays:

void daa( int n )
{
int *x;
int i;

x = malloc( n * sizepf *x );
if ( x == NULL )
{
fprintf( stderr, "Can't allocate memory\n" );
exit( EXIT_FAILURE );
}

for ( i = 0; i < n; i++ )
x[ i ] = i;

free( x );
}


But how can we allocate a dynimic mem for an array
In the code above it is *x but what can we do if x is decleared as a array?

This is legal even with C89. Of course 'x' isn't a real array but just
a pointer to some memory that can hold the number of integers you need.
And in many places 'x' can be treated like a real array, but there are
subtle differences, e.g. sizeof x is not the amount of memory it's
pointing to but the size of a pointer. And, of course, you must free()
the memory you allocated when you don't need it anymore.

Regards, Jens


Thanks for all the answers
Nov 13 '05 #5
da***********@y ahoo.com wrote:
Je***********@p hysik.fu-berlin.de wrote in message news:<bl******* *****@uni-berlin.de>...
On the other had you have dynamically allocated arrays:

void daa( int n )
{
int *x;
int i;

x = malloc( n * sizepf *x );
if ( x == NULL )
{
fprintf( stderr, "Can't allocate memory\n" );
exit( EXIT_FAILURE );
}

for ( i = 0; i < n; i++ )
x[ i ] = i;

free( x );
}
But how can we allocate a dynimic mem for an array
In the code above it is *x but what can we do if x is decleared as a array?


You can't change the length of an array once you have created it. If
you need dynamically resizeable arrays you must work with pointers and
use malloc()/realloc() to change the amount of memory they point to.
If you look up how other languages implement arrays of non-fixed
length (e.g. in Perl) you will find that they often are written in C
and actually use malloc()/realloc() to achieve this effect.

Regards, Jens
--
_ _____ _____
| ||_ _||_ _| Je***********@p hysik.fu-berlin.de
_ | | | | | |
| |_| | | | | | http://www.physik.fu-berlin.de/~toerring
\___/ens|_|homs|_|oe rring
Nov 13 '05 #6

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

Similar topics

6
2751
by: BigDadyWeaver | last post by:
I am using the following code in asp to define a unique and unpredictable record ID in Access. <% 'GENERATE UNIQUE ID Function genguid() Dim Guid guid = server.createobject("scriptlet.typelib").guid guid=Left(guid,instr(guid,"}")) genguid=guid
13
21376
by: HappyHippy | last post by:
Hi, I'm wondering what you think about this piece of code: #include<iostream> int main() { int size; std::cin >> size;
27
2634
by: Mike P | last post by:
I will be passing my function a two dimensional array of varying length. Within that array is one data point, and the number of times it should loop through. So, for example, I might pass this to the function: example = new Array("A",2); example = new Array("Q",4); function loopIt(example);
2
6445
by: Augusto Cesar | last post by:
Hello people. How can I Pass ASP Array variable to Javascript; I´m to trying this: <script language="JavaScript"> var x = new Array(10);
8
1786
by: lovecreatesbeauty | last post by:
Hello experts, I have seen following the code snippet given by Marc Boyer (with slight changes by me for a better format), and have doubts on it. I am so grateful if you can give me your kindly help and hints on this problem. 1. Does the function call `foo(3, 3, tab);' refer to the data outside the array `int tab;'. The available subscription for a 3X3 2-D array should be 0..2 X 0..2, I think.
6
2711
by: foreverbored75 | last post by:
Hello All! I am just learning c++ in school and I have the following question: Is there a way for the user to input the length of an array (console application) without using another variable? I made this program that finds the average of x number of numbers and stores the average in the last index of the array of the numbers. The other other variable I have is to determine the length of the array (totalNums). Is there a way to get...
18
4064
by: Pedro Pinto | last post by:
Hi there once more........ Instead of showing all the code my problem is simple. I've tried to create this function: char temp(char *string){ alterString(string); return string;
13
7811
by: lak | last post by:
I want to know what is the variable length in c. I K&R they stated that atleast 31 character. But I give 1 lakhs length to a variable, but my compiler doesn't say any error. It accepts it.Then what is the maximum length to a variable name.?
7
2799
by: Cromulent | last post by:
In section 6.7.5.2 it states the following: If the size is not present, the array type is an incomplete type. If the size is*instead of being an expression, the array type is a variable length array type of unspecified size, which can only be used in declarations with function prototype scope;124) such arrays are nonetheless complete types. If the size is an integer constant expression and the element
0
9645
marktang
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, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
10327
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...
1
10092
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
9950
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
8973
agi2029
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 projectplanning, coding, testing, and deploymentwithout 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...
0
5381
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...
1
4053
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
2
3647
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2879
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.