Re: Pro*C ANSI C Variable Length Strings

From: Jeffery Cann <jcann_at_fairway.com>
Date: 1998/02/10
Message-ID: <34E0BF31.906A618_at_fairway.com>#1/1


Don Hillsberry wrote:
>
> I am writing a large group of ANSI C programs to perform all manner of
> processing with hundreds of tables in Oracle. I am looking for some advise
> or discussion to help explain the different character/string external
> datatypes and when I should use one type versus another. I am specifically
> concerned about the variable length string type for columns defined as
> VARCHAR2. I have read the Pro*C manual and I think I'm more confused.
>
> The VARCHAR type looks cumbersome requiring special handling for strings
> with/without nulls, but doesn't the STRING type require a SQL EXEC VAR
> statement for every column?
>
> Does anyone have some specific reasons why not to use one or the other?
> Any help will be greatly appreciated.....
>
> DonHillsberry_at_worldnet.att.net

Don't be confused by the Oracle manual. The VARCHAR datatype is acutally implemented as a structure in C. The data structure has the following form:

(gdb) p m_cancel
$1 = {
  len = 1,
  arr = "Y\000"
}
(gdb)

Where m_cancel.len carries the length (in bytes) of the string read from the database and the m_cancel.arr carries the actual value of the string. In this case, the VARCHAR variable m_cancel is a 1 byte string with the value of 'Y'.

For the VARCHAR string, to copy data into the string:

        strcpy("string to copy", string.arr);

To assign the length of the string:

        string.len = strlen(string);

To NULL terminate the string:

        string.len+1 = '\0';

The VARCHAR datatype is quite useful because it has the length assigned on output from the database. This means you don't have to use a call to strlen and you can do useful stuff like this:

	VARCHAR oracle_string[80];
	char 	new_string[20];

	strncpy(new_string, oracle_string, oracle_string.len);

Thus, you know the sizeof the oracle_string from its len field.

Cheers.
Jeff

-- 
Senior Software Engineer
Fairway Systems, Inc.
jcann_at_fairway.com
Received on Tue Feb 10 1998 - 00:00:00 CET

Original text of this message