473,888 Members | 1,616 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Find the size of an array

I want to create a new array of the same size of an array already
available:
#include <stdio.h>
#include <string.h>

int main(void)
{
char arrc[] = "URI";
const int asize = sizeof(arrc) / sizeof (arrc[0]);
char new_arr[asize];

printf("new_arr size = %d\n", sizeof(new_arr) );

return 0;
}

=============== ========= OUTPUT =============== =====
[arnuld@dune C]$ gcc4 -ansi -pedantic -Wall -Wextra test.c
test.c: In function ‘main’:
test.c:9: warning: ISO C90 forbids variable-size array ‘new_arr’
[arnuld@dune C]$ ./a.out
new_arr size = 4
[arnuld@dune C]$

The program gives correct answer. But Why the warning. sizeof() is compile
time operator then why do I get some warning related to run-time ?


--
www.lispmachine.wordpress.com
my email is @ the above blog.
Google Groups is UnBlocked now :)
Nov 6 '08 #1
24 2954
arnuld said:
I want to create a new array of the same size of an array already
available:
#include <stdio.h>
#include <string.h>

int main(void)
{
char arrc[] = "URI";
const int asize = sizeof(arrc) / sizeof (arrc[0]);
char new_arr[asize];

printf("new_arr size = %d\n", sizeof(new_arr) );

return 0;
}

=============== ========= OUTPUT =============== =====
[arnuld@dune C]$ gcc4 -ansi -pedantic -Wall -Wextra test.c
test.c: In function ?main?:
test.c:9: warning: ISO C90 forbids variable-size array ?new_arr?
[arnuld@dune C]$ ./a.out
new_arr size = 4
[arnuld@dune C]$

The program gives correct answer. But Why the warning. sizeof() is
compile time operator then why do I get some warning related to run-time
?
gcc is being a little terse here (for understandable reasons). Yes,
sizeof's result is evaluated by the compiler. But, by the time the
compiler is looking at new_arr, it's forgotten all about the sizeof in the
previous line. All it can see is that you've got this asize thing, which
is a const int *but NOT an integral constant expression* - a puzzling
distinction, but a very real one in C.

You can get what you want, however, by cutting out the middle-man:

char arrc[] = "URI";
char new_arr[sizeof arrc / sizeof arrc[0]];

--
Richard Heathfield <http://www.cpax.org.uk >
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Nov 6 '08 #2
Michael <mi*****@michae ldadmum.no-ip.orgwrites:
arnuld wrote:
>I want to create a new array of the same size of an array already
available:
#include <stdio.h>
#include <string.h>
int main(void)
{
char arrc[] = "URI";
const int asize = sizeof(arrc) / sizeof (arrc[0]);
char new_arr[asize];
printf("new_arr size = %d\n", sizeof(new_arr) );
return 0;
}
============== ========== OUTPUT =============== =====
[arnuld@dune C]$ gcc4 -ansi -pedantic -Wall -Wextra test.c
test.c: In function ¡main¢:
test.c:9: warning: ISO C90 forbids variable-size array ¡new_arr¢
[arnuld@dune C]$ ./a.out new_arr size = 4
[arnuld@dune C]$ The program gives correct answer. But Why the
warning. sizeof() is compile
time operator then why do I get some warning related to run-time ?
I have a warning on line 10. Use %lu instead of %d solves it.
It solves it only if size_t happens to be a typedef for unsigned long.
For C90, the portable solution is to use "%lu" *and* convert the
sizeof expression to unsigned long:

printf("new_arr size = %lu\n", (unsigned long)sizeof new_arr);
There is
no problems elsewhere.
As I think has already been mentioned in this thread, asize is not a
constant expression, so it can't be used as an array size in C90. In
C99, new_arr is a VLA (variable-length array). A solution to this
that's portable to both C90 and C99 has already been posted: use
"sizeof arrc / sizeof arrc[0]" directly as the array size.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Nov 7 '08 #3
On Thu, 06 Nov 2008 06:54:12 +0000, Richard Heathfield wrote:

gcc is being a little terse here (for understandable reasons). Yes,
sizeof's result is evaluated by the compiler. But, by the time the
compiler is looking at new_arr, it's forgotten all about the sizeof in the
previous line. All it can see is that you've got this asize thing, which
is a const int *but NOT an integral constant expression* - a puzzling
distinction, but a very real one in C.
Now what is the difference between a "const int" and an "inegeral constant
expression". I can't seem to understand it. May I have 2 examples
showing the distinction, so that I can comprehend something out of them.
You can get what you want, however, by cutting out the middle-man:
char arrc[] = "URI";
char new_arr[sizeof arrc / sizeof arrc[0]];

That works fine. Now the real problem is to understand the confusing
distinction.

--
www.lispmachine.wordpress.com
my email is @ the above blog.
Nov 7 '08 #4
arnuld said:
>On Thu, 06 Nov 2008 06:54:12 +0000, Richard Heathfield wrote:

>gcc is being a little terse here (for understandable reasons). Yes,
sizeof's result is evaluated by the compiler. But, by the time the
compiler is looking at new_arr, it's forgotten all about the sizeof in
the previous line. All it can see is that you've got this asize thing,
which is a const int *but NOT an integral constant expression* - a
puzzling distinction, but a very real one in C.

Now what is the difference between a "const int" and an "inegeral
constant expression". I can't seem to understand it. May I have 2
examples showing the distinction, so that I can comprehend something out
of them.
A const int is simply an int that you've promised not to change, by
"decorating " it with the word "const".

On the other hand, "integral constant expression" is a formal term that is
relevant to a number of aspects of C programming, amongst them the number
of elements specified in an array (or, in the case of C99, a non-VL array)
at the time of its declaration.

So - what characteristics does an integral constant expression have? "An
integral constant expression shall have integral type and shall only have
operands that are integer constants, enumeration constants, character
constants, sizeof expressions, and floating constants that are the
immediate operands of casts."

Examples of integer constants: 0, 6, 42
Examples of character constants: 'A', 'z', '.'
Example of sizeof expression: sizeof otherarray / sizeof otherarray[0]
Example of floating constants that are the immediate operands of casts:
(int)3.14159

--
Richard Heathfield <http://www.cpax.org.uk >
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Nov 7 '08 #5
>Now what is the difference between a "const int" and an "inegeral constant
>expression".
A const int is "const" but not "ant". That is, it's not a compile-time
constant. Why? Because the standard says so. Generally, anything
that requires accessing memory is not a compile-time constant, even
something like "Hello"[0], which should be equal to 'H'.

An "integral constant expression" is constant (including at
compile-time), by definition.

const int not_constant = 42;

switch(c)
{
case 42: /* allowed */
break;
case not_constant: /* not allowed */
break;
}
>I can't seem to understand it. May I have 2 examples
showing the distinction, so that I can comprehend something out of them.
Note that "const" means more that "YOU cannot write it" not "NOBODY
can write it". This is a perfectly logical declaration:

extern const volatile time_t hardware_real_t ime_clock;

although how you define the variable requires something outside
Standard C if the variable name is descriptive of what it actually
is. It changes by itself with time. YOU may not set it.

Nov 7 '08 #6
On Fri, 07 Nov 2008 07:09:26 +0000, Richard Heathfield wrote:
A const int is simply an int that you've promised not to change, by
"decorating " it with the word "const".

So compiler can change it, I can not ?

On the other hand, "integral constant expression" is a formal term that is
relevant to a number of aspects of C programming, amongst them the number
of elements specified in an array (or, in the case of C99, a non-VL array)
at the time of its declaration.
So - what characteristics does an integral constant expression have? "An
integral constant expression shall have integral type and shall only have
operands that are integer constants, enumeration constants, character
constants, sizeof expressions, and floating constants that are the
immediate operands of casts."
Examples of integer constants: 0, 6, 42
Examples of character constants: 'A', 'z', '.'
Example of sizeof expression: sizeof otherarray / sizeof otherarray[0]
Example of floating constants that are the immediate operands of casts:
(int)3.14159

Therefore array depends on an "integral constant expression" not a
constant integer. IOW, should I stop using const and start using enum for
a real constant ?

--
www.lispmachine.wordpress.com
my email is @ the above blog.
Nov 7 '08 #7
arnuld wrote:
>
Therefore array depends on an "integral constant expression" not a
constant integer. IOW, should I stop using const and start using enum for
a real constant ?
Due to the broken nature of const in C, yes if you want a compile time
constant.

const is fine when an integral constant expression is not required.

--
Ian Collins
Nov 7 '08 #8
arnuld <su*****@invali d.addresswrites :
>On Thu, 06 Nov 2008 06:54:12 +0000, Richard Heathfield wrote:
gcc is being a little terse here (for understandable reasons). Yes,
sizeof's result is evaluated by the compiler. But, by the time the
compiler is looking at new_arr, it's forgotten all about the sizeof in the
previous line. All it can see is that you've got this asize thing, which
is a const int *but NOT an integral constant expression* - a puzzling
distinction, but a very real one in C.

Now what is the difference between a "const int" and an "inegeral constant
expression". I can't seem to understand it. May I have 2 examples
showing the distinction, so that I can comprehend something out of them.
The tricky thing is that "const" does *not* mean "constant" -- or
rather "const" doesn't mean what C means by "constant". And yes, it's
a poor choice of words, but we're stuck with it, even though the word
"const" obviously is derived from the English word "constant".

"const" really means "read-only". If an object is declared "const",
then attempting to modify it is a constraint violation.

"constant", as in "constant expression", means roughly that the
expression can be evaluated at compile time. I say "roughly" because
that's not how the standard defines it; the standard restricts the
kinds of things that can appear in a constant expression. All
constant expressions can be evaluated at compile time, but not all
expressions that can be evaluated at compile time (by a sufficiently
clever compiler) are "constant expressions". Basically, the language
doesn't require the compiler to be *too* clever.

For example, this is perfectly legal:

const int r = rand();
const time_t start_time = time(NULL);

In both cases the initial value can't be computed until run time; the
"const" says that you're not allowed to modify the object once it's
been initialized. (You can *attempt* do modify it via a tricky
pointer cast, but that's undefined behavior.)

And here's another example where "const" is definitely not constant:

int var = 42;
const int *ptr = &var; /* pointer to const int */
var = 43; /* perfectly legal */
*ptr = 44; /* bzzzt! *ptr is const; you're not allowed
to change it */

Here the object has two "names", var and *ptr. The object itself
isn't read-only, but one of its two "names" is read-only. (The
standard doesn't use the word "name" this way, thus the quotation
marks.)

Another way to look at it: applying "const" to something asks the
compiler to complain if you attempt to modify it.

Now if I declare
const int x = 100;

then the compiler is certainly free to evaluate x at compile time,
replacing any reference to x with a literal 100. That's just a matter
of optimization; it doesn't change the visible behavior of the
program. What the compiler *can't* do is allow you to use "x" in a
context that requires a constant expression -- such as (in C90) an
array length.

(And yes, I'm using the word "allow" a bit loosely here; compilers can
permit such things, but you can't depend on it.)

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Nov 7 '08 #9
arnuld wrote:
I want to create a new array of the same size of an array already
available:
#include <stdio.h>
#include <string.h>

int main(void)
{
char arrc[] = "URI";
const int asize = sizeof(arrc) / sizeof (arrc[0]);
char new_arr[asize];

printf("new_arr size = %d\n", sizeof(new_arr) );

return 0;
}

=============== ========= OUTPUT =============== =====
[arnuld@dune C]$ gcc4 -ansi -pedantic -Wall -Wextra test.c
test.c: In function ‘main’:
test.c:9: warning: ISO C90 forbids variable-size array ‘new_arr’
[arnuld@dune C]$ ./a.out
new_arr size = 4
[arnuld@dune C]$

The program gives correct answer. But Why the warning. sizeof() is compile
time operator then why do I get some warning related to run-time ?

I have a warning on line 10. Use %lu instead of %d solves it. There is
no problems elsewhere.
Nov 7 '08 #10

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

Similar topics

4
3860
by: Greg Baker | last post by:
I don't know what standard protocol is in this newsgroup. Am I allowed to post code and ask for help? I hope so.. :) Here's my problem: I am trying problem 127 of the valladolid online contests (http://online-judge.uva.es/p/v1/127.html). The program I wrote seems to work fine, but it takes way too much memory to run. I am not that good at programming C++, unfortunately, so I can't seem to find my memory leak. As far as I can tell,...
13
34418
by: Noah Spitzer-Williams | last post by:
Hello guys, I would like to do something seemingly simple: find out if an element in an array that is passed to my function exists. I used to think I could just do: if (arr) ... However, if this element's value happens to be 0, the conditional will return false, even though the element actually exists. Any ideas? Can you check if the element == null?
11
3623
by: Sontu | last post by:
Consider the following code: int main(void) { char buffer; func(buffer); } void func(char *bufpas) {
5
5602
by: nmtoan | last post by:
Hi, I could not find any answer to this simple question of mine. Suppose I have to write a program, the main parts of it are as follows: #include <blahblah.h> struct {
3
3183
by: Poewood | last post by:
Okay here are four classes for a pocket pc program: Input, fpositional, ComboBoxArray and TextBoxArray. The "input" class is the form. I use the fpositional class to handle most of the functions for the objects on the form, in addition the The objects are created in the fpositional class and affixed to the Input form through the fpositional constructor which takes the form as an argument. The ComboBox and TextBox Array classes hold the...
6
17356
by: finerrecliner | last post by:
hey everyone i'm trying to make a function that will return the length and width of a dynamically allocated 2D array. here's what i came up with to find width: int findWidth(int** matrix) { int width = 0;
2
2654
choke
by: choke | last post by:
I need to write a function in devc++ that creates an array of n integers, each element is equal to n*n+i*i-n*i where i is from 0 to n-1 as the array index. Within the same function I need to find the maximum value, minimum value and average of all elements. I'm stuck on the first one :/ I've practiced calling another function to find the maximum, and that seemed to work fine. I get a number in the millions when trying to do this all in one...
11
7716
by: C C++ C++ | last post by:
Hi all, got this interview question please respond. How can you quickly find the number of elements stored in a a) static array b) dynamic array ? Rgrds MA
2
6669
by: karinmorena | last post by:
I'm having 4 errors, I'm very new at this and I would appreciate your input. The error I get is: Week5MortgageGUI.java:151:cannot find symbol symbol: method allInterest(double,double,double) Location: class Week5MortgageGUI Week5MortgageLogic allint = logic.allInterest(amount, term, rate); Week5MortgageGUI.java:152:cannot find symbol symbol: method allInterest(double,double,double) Location: class Week5MortgageGUI
0
10777
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
10882
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
10438
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...
1
7990
isladogs
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...
0
7148
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
5817
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
6014
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4642
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
4243
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.