472,958 Members | 2,180 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,958 software developers and data experts.

Difference between char array and a null terminated string?

Hi experts,

I'm from a Verilog HDL background and trying to learn C. There are a lot of similarities between Verilog and C but the concept of char arrays and strings has me confused. I'd appreciate any help or pointers here.

This is the code, nothing fancy, just basic experiments around char array and string,

#include <stdio.h>
#include <string.h>

int main() {

char test1[5];
char test2[5];

int i;

test[0] = 'a';
test[1] = 'b';
test[2] = 'c';
test[3] = 'd';
test[4] = 'e';
test[5] = 'f';

strcpy (test2, test1);

for (i = 0; i < 6; i = i + 1)
printf("%c\n", test2[i]);

return(0);
}

I was expecting this code to fail during compilation (I'm using GCC version 3.2.3 on RHEL 3.0) because I'm exceeding the array bounds with the assignments. What is more surprising to me is that all the characters (a-f) do get printed. Any ideas why? The program output is this,

[nageshg@lx-nageshg mywork]$ a.out
a
b
c
d
e
f
[nageshg@lx-nageshg mywork]$

Another doubts is, what about the null terminating character in this case? I read that if a char array is initialized like this,

char test1[5] = "test";

the last (unassigned) character is set to '\0' and this variable becomes a string as opposed to just an array of characters. But if I initialize it character by character (as I did in the program above), I have to take care to set the last character to '\0' myself. Moreover it is said that the string handling functions expect a null terminated string as their arguments. But in the code above, this doesn't seem true. So why does strcpy() work?

I guess my basic doubt here is, what is the difference between an array of characters and a string in C? Or is it that they are one and the same thing, regardless of how I initialize and whether or not the last character is set to '\0'?

This essential point seems to have been deliberately evaded in the book I'm reading (or I may be missing the point myself). Please help.

BTW, if I remove the for loop in the code above and use the printf with the string format specifier,

printf("%s\n", test2);

I see abcdef as the output.

Thanks,
Nagesh

P.S. I did search the forum before deciding to post this. There doesn't seem to be anything dealing directly with something this basic.
Mar 8 '08 #1
2 7062
Banfa
9,065 Expert Mod 8TB
I was expecting this code to fail during compilation (I'm using GCC version 3.2.3 on RHEL 3.0) because I'm exceeding the array bounds with the assignments. What is more surprising to me is that all the characters (a-f) do get printed. Any ideas why?
...

Another doubts is, what about the null terminating character in this case? I read that if a char array is initialized like this,

char test1[5] = "test";

the last (unassigned) character is set to '\0' and this variable becomes a string as opposed to just an array of characters. But if I initialize it character by character (as I did in the program above), I have to take care to set the last character to '\0' myself. Moreover it is said that the string handling functions expect a null terminated string as their arguments. But in the code above, this doesn't seem true. So why does strcpy() work?

I guess my basic doubt here is, what is the difference between an array of characters and a string in C?
OK your program is confusing you because it is apparently working even though you think have done something wrong. The problem is that you call to strcpy does cause an out of bounds array access and this invokes undefined behaviour.

Undefined behaviour is a bad thing, the problem with it is that the behaviour of the program becomes completely undefined, anything might happen. This includes a memory exception, formatting your hard disk or working correctly. These are all examples (more or less extreme) of undefined behaviour but this is by no means an exhaustive list.

The undefined behaviour that you have run into is "program works as expected despite being wrong" which is what is confusing you.

You basic assertion about C strings and char arrays is correct, the only difference is that the string must have a character value '\0' (0) at the end of it.

It is likely that what ever data follows test1 in your program incidentally happens to be '\0' (0). It might be worth printing both test1 and test2 using %s at the end of your program you may then see unexpected behaviour.

You program does not explicitly cause an out of bounds array access and hence your compiler does not catch it, but when you call strcpy using an unterminated source string you implicitly get an out of bounds array access, undefined behaviour is invoked and the output of your program becomes moot it may do anything at that point.

You compiler can not catch this sort of error which is why static analysis tools exist (pclint, splint). You run you code through these programs and they produce extra errors and warning about what your program may be doing. A static analysis tool may well catch the error in this code.


So in conclusion, you are right about the difference between strings and array of char. Not terminating your strings is BAD, your compiler may not notice the problem and the program may appear to work but you are creating a problem waiting to happen at a future date normally at the most convent time. Be very careful not to do it.
Mar 8 '08 #2
Thanks for the reply. That helps clear some of the confusion. But I guess it will take me some time to get used to this ambiguity in C. Verilog is strictly governed by the IEEE LRM. The behavior is never undefined.

But yes, the whole purpose of an HDL (like Verilog) and a general purpose software programming language (like C) is different.

cheers!!
--Nagesh
Mar 11 '08 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

19
by: Rick | last post by:
Hi, I was wondering, can it be safely assumed that any function that returns a *char will return a NULL terminated string? Or does the function explicitly mention this always (and the ones that...
2
by: vikas | last post by:
I have following structure in c++. typedef struct MMF_result_struct { int action; char text; int cols,rows; int month,day,year; } MMF_result; Now this structure is shared between C++ and C#...
3
by: Asha | last post by:
greetings, i have some questions below, what are the differences between private string _strVal = string.Empty; and _strVal = null; does the string.Empty; allocate memory for it? how about...
3
by: kaizen | last post by:
Hi, i wrote the code in C and compiled in VC++ compiler. at that time it has thrown the below mentioned error. error C2664: 'strcpy' : cannot convert parameter 2 from 'char' to 'const char *'...
8
by: Henning M | last post by:
Hi, I'm trying to use stringbuilder to collect a list of strings. (as suggested by Claes Bergefall) Declare Auto Function CM_Get_Device_ID_List Lib "cfgmgr32.dll" (ByVal pszFilter As String,...
10
by: fei.liu | last post by:
Consider the following sample code char * ptr = "hello"; char carray = "hello"; int main(void){ } What does the standard have to say about the storage requirement about ptr and carray? Is...
3
by: =?Utf-8?B?cmtwYXQ=?= | last post by:
i'm calling a C++ DLL from C#. here's C++ interface: char* __cdecl SendCmd(void* handle, char* cmd, char* data, char* buffer); here's my call in C#: unsafe public static extern byte* SendCmd...
45
by: anto frank | last post by:
hi friends, is ther any difference in array in c and array in c++?
11
by: Dennis Jones | last post by:
Hi all, 1) Let's say you have two char 's of the same size. How would you write a no-fail swap method for them? For example: class Test { char s; void swap( Test &rhs ) {
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
2
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

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.