GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 25-Apr-2006, 11:49
earachefl earachefl is offline
Member
 
Join Date: Feb 2006
Posts: 178
earachefl is on a distinguished road

? re strings as character arrays function


I can't figure out why I'm getting compiler errors for the following code:
CPP / C++ / C Code:
#include <iostream>
#include <string>
using namespace std;

void concat (const char[], const char[], char[], int&);

int main () {

    int finalSize;
    char charArray1 [] = "Mambo everybody";
    char charArray2 [] = "You must obey!!!";
    finalSize = strlen(charArray1) + strlen(charArray2) + 2;
    char finalArray [finalSize];
    
    concat (charArray1, charArray2, finalArray, finalSize);
    
    cout << "Result of concatenation of character arrays <"
         << charArray1 << "> and <" << charArray2 << "> is " << finalArray << endl;
    return 0;
}

void concat (const char[] str1, const char[] str2, char[] result, int& size)
{
    int size1 = strlen(str1);
    int size2 = strlen(str2);
    int j, k;                               //counter variables
    
    //Store char array str1 into char array result
    for (j = 0; j < size1; j++) {
        result[j] = str1[j];
    }
    result[j] = ' ';                        //Store space in char array result after str1
    
    //Store char array str2 into char array result after str1
    k = 0;
    for (j = size1 + 1; j < size2; j++) {
        result[j] = str2[k];
        k++;
    }
    result[j] = '\0';                       //Store null character at end of char array result
}
Error messages are:

Quote:
main.cpp:22: error: expected ',' or '...' before 'str1'
main.cpp:24: error: 'str1' was not declared in this scope
main.cpp:25: error: 'str2' was not declared in this scope
main.cpp:30: error: 'result' was not declared in this scope
main.cpp:32: error: 'result' was not declared in this scope
Compiler is XCode 2.2
  #2  
Old 25-Apr-2006, 12:30
Sokar Sokar is offline
Member
 
Join Date: May 2005
Posts: 243
Sokar has a spectacular aura aboutSokar has a spectacular aura about

Re: ? re strings as character arrays function


When you declare an array do you do this,
CPP / C++ / C Code:
 char[] str1
or
CPP / C++ / C Code:
char str1[]
Also this is wrong.
CPP / C++ / C Code:
char finalArray [finalSize];
The array size should be a constant if you are not using new/delete. I will not debate the issue. Do what you want but it is wrong.
  #3  
Old 25-Apr-2006, 12:39
earachefl earachefl is offline
Member
 
Join Date: Feb 2006
Posts: 178
earachefl is on a distinguished road

Re: ? re strings as character arrays function


Quote:
Originally Posted by Sokar
When you declare an array do you do this,
CPP / C++ / C Code:
 char[] str1
or
CPP / C++ / C Code:
char str1[]
D'oh!!!
Quote:
Also this is wrong.
CPP / C++ / C Code:
char finalArray [finalSize];
The array size should be a constant if you are not using new/delete. I will not debate the issue. Do what you want but it is wrong.
I don't understand... My textbook doesn't say you can't do that. Is this only in reference to character arrays?
  #4  
Old 25-Apr-2006, 12:41
earachefl earachefl is offline
Member
 
Join Date: Feb 2006
Posts: 178
earachefl is on a distinguished road

Re: ? re strings as character arrays function


Actually, never mind, the book does say:
Quote:
The size value must be a constant expression consisting of constant values and constant identifiers. This value must be an integer and must be greater than or equal to 1.
  #5  
Old 25-Apr-2006, 12:48
earachefl earachefl is offline
Member
 
Join Date: Feb 2006
Posts: 178
earachefl is on a distinguished road

Re: ? re strings as character arrays function


So in this rudimentary phase of programming (without dynamic structures) there's no way to change the size of an array with a variable, even when first initializing it? That seems a bit restrictive - I can see how changing the size of an array after initializing it could wreak havoc, but how could initializing with a variable cause a problem?

File under "things that make you go "Hmmmmmmm"", I guess......
  #6  
Old 25-Apr-2006, 13:02
Sokar Sokar is offline
Member
 
Join Date: May 2005
Posts: 243
Sokar has a spectacular aura aboutSokar has a spectacular aura about

Re: ? re strings as character arrays function


Quote:
Originally Posted by earachefl
So in this rudimentary phase of programming (without dynamic structures) there's no way to change the size of an array with a variable, even when first initializing it?
No.
Quote:
Originally Posted by earachefl
That seems a bit restrictive - I can see how changing the size of an array after initializing it could wreak havoc, but how could initializing with a variable cause a problem?
It does not cause problems when you use new/delete. I know what you are saying and I do not know the answer that. So hopefully someone else can provide an answer.


I now that some standards of "c" it is allowed. You should be able to check your compiler documentation to see what to change to flag it as an error. If you need help with that just post what compiler and operating system you are using and someone may be able to suggest the solution to flag that as an error.
  #7  
Old 25-Apr-2006, 13:40
earachefl earachefl is offline
Member
 
Join Date: Feb 2006
Posts: 178
earachefl is on a distinguished road

Re: ? re strings as character arrays function


Quote:
Originally Posted by Sokar

I now that some standards of "c" it is allowed. You should be able to check your compiler documentation to see what to change to flag it as an error. If you need help with that just post what compiler and operating system you are using and someone may be able to suggest the solution to flag that as an error.
Yes, I can use a variable or a variable expression to declare array size in my compiler. I'm using XCode 2.2, OS 10.4.5. So you're saying that technically it's illegal, but some compilers allow it? My brain is starting to hurt.......
  #8  
Old 25-Apr-2006, 16:08
WaltP's Avatar
WaltP WaltP is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Midwest US
Posts: 3,373
WaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to all

Re: ? re strings as character arrays function


Quote:
Originally Posted by earachefl
So in this rudimentary phase of programming (without dynamic structures) there's no way to change the size of an array with a variable, even when first initializing it? That seems a bit restrictive - I can see how changing the size of an array after initializing it could wreak havoc, but how could initializing with a variable cause a problem?
When you initialize an array the way you need to, the space for the array is created at compile time. It is static.

If you create the array via a variable, by definition it is dynamic. IOW the array must be created after the program starts execution because the value of the variable isn't know until after execution starts. The space for the array therefore comes from free memory.
__________________

The 3 Laws of the Procrastination Society:
1) Never do today that which can be put off until tomorrow
2) Tomorrow never comes
  #9  
Old 25-Apr-2006, 16:35
Sokar Sokar is offline
Member
 
Join Date: May 2005
Posts: 243
Sokar has a spectacular aura aboutSokar has a spectacular aura about

Re: ? re strings as character arrays function


Quote:
Originally Posted by earachefl
Yes, I can use a variable or a variable expression to declare array size in my compiler. I'm using XCode 2.2, OS 10.4.5. So you're saying that technically it's illegal, but some compilers allow it? My brain is starting to hurt.......
Yes, it is illegal. I am not going to dig deep to prove it but here is this,
http://msdn2.microsoft.com/en-US/lib...2e(VS.80).aspx
Quote:
2. The declarator:

*The identifier.
*A constant expression of integral type enclosed in brackets, [].
I sure it is in here if you want to look. The standard from October 1997. Yes it is old but I am sure that part has not changed.
http://www.open-std.org/jtc1/sc22/wg...wp/html/oct97/
  #10  
Old 25-Apr-2006, 16:59
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 5,311
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: ? re strings as character arrays function


Quote:
Originally Posted by Sokar
Yes, it is illegal. I am not going to dig deep to prove it but here is this,
http://msdn2.microsoft.com/en-US/lib...2e(VS.80).aspx

I sure it is in here if you want to look. The standard from October 1997. Yes it is old but I am sure that part has not changed.
http://www.open-std.org/jtc1/sc22/wg...wp/html/oct97/

Current versions of GNU C compilers support most of the features of the so-called "C99" Standard (ISO/IEC 9899:1999), including Variable Length Arrays (VLAs). GNU C++ compilers also allow Variable Length Arrays, even though they are not included in the C++ standard (ISO/IEC 14882:2003).

The Borland and Microsoft compilers to which I have access do not support VLAs (or much of anything else beyond the older "C89" standard, and in fact, not all of those features). I have seen no evidence that either company has plans to extend C compiler features to the additional ones in the C99 standards. Borland has re-invented itself yet again (this week), and Microsoft is, well, Microsoft.

If you have a GNU C compiler, you can compile programs with VLAs (under the conditions set forth in the Standard--- See Footnote).

You could try the following:
CPP / C++ / C Code:
#include <stdio.h>

int main()
{
  int size;

  printf("Enter an integer: ");
  if (scanf("%d", &size) != 1) {
    return 0;
  }
  printf("Now declaring an array if chars with size = %d\n", size);

  char test[size];

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

  return 0;
}

If you just execute "gcc z.c" it compiles and works (for me, at least with cygwin/gcc on Windows XP and on Linux with gcc version 3.4.x or 4.x).

If you try "gcc z.c -Wall -pedantic", however, you will see warning messages, something like:
Code:
z.c:14: warning: ISO C90 forbids variable-size array `test' z.c:14: warning: ISO C90 forbids mixed declarations and code
(It still produces a viable executable, in spite of the warnings, even if you add "-ansi")

However if I execute "gcc z.c -Wall -pedantic --std=c99" it's happy again. (No warnings, and it still works.)

For C++, you can try the following:

CPP / C++ / C Code:
#include <iostream>

using namespace std;

int main()
{
  int size;

  cout << "Enter an integer: ";
  cin >> size;
  if (!cin) {
    return 0;
  }
  cout << "Now declaring an array if chars with size = " << size << endl;

  char test[size];

  cout << "sizeof(test) = " << sizeof(test) << endl;

  return 0;
}

Now, "g++ z.cpp" gives a working executable with no compiler messages, but if you execute "g++ z.cpp -Wall -pedantic", you will get messages, something like
Code:
z.cpp: In function `int main()': z.cpp:13: error: ISO C++ forbids variable-size array `test'

This time: no executable; it's really an error.

My recommendation (especially for programmers-in-training) is usually to stick with the C89 standard for C programs (if it ain't in K&R2: fuggedaboudit) and for the current C++ standard for those programs. (But that's just me --- I'm funny that way.)

In my opinion, for C++ programs, the availability of STL vectors and strings obviates the need for VLAs in many, many, many cases. C programmers can use malloc() and free(), the way that we have always done.

Regards,

Dave

Footnote --- from ISO/IEC 9899:1999 Paragraph 6.7.5.2

"All declarations of variably modified (VM) types have to be at either block scope or function prototype scope. Array objects declared with the static or extern storage-class specifier cannot have a variable length array (VLA) type. However, an object declared with the static storageclass specifier can have a VM type (that is, a pointer to a VLA type). Finally, all identifiers declared with a VM type have to be ordinary identifiers and cannot, therefore, be members of structures or unions."

That's clear enough for me.
Last edited by davekw7x : 25-Apr-2006 at 17:36.
 
 

Recent GIDBlogProblems with the Navy (Officers) by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

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

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
[Include] Doubly-linked List dsmith C Programming Language 6 14-Apr-2006 13:12
[Tutorial] Function Pointers aaroncohn C++ Forum 4 17-Feb-2006 11:33
[GIM] gim.h dsmith C Programming Language 0 18-Jan-2005 08:48
Revising Script style ?????? pepee MySQL / PHP Forum 4 14-Apr-2004 04:59

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 18:39.


vBulletin, Copyright © 2000 - 2010, Jelsoft Enterprises Ltd.