简体   繁体   中英

In a C function what's the difference between char and string?

I'm using a template from my teacher and at the beginning of the code is says:

#include "lab8.h"

void main(void)
{
int response;
int count;
string words[MAX_COUNT];

Later on in the function, a whole lot of words get put inside the words string. So I was like looking at that last line and got confused. I thought char declared strings? What does that last line even do? I also noticed in a couple of function parameter lists later on, there was entered "string words" instead of what I expected that mention char or something.

EDIT:

typedef char string[MAX_LENGTH];

had been written in the .h file didn't see it.

C does not have a basic data type called string .

Check the lab8.h file carefully. Usually, string should be a typedef of unsigned char .

Essentially, string words[MAX_COUNT]; defines an array of variable type string containing MAX_COUNT number of variables.

C does not have a dedicated string data type. In C, a string is a sequence of character values followed by a zero-valued byte. Strings are stored as arrays of char , but not all arrays of char contain strings.

For example,

char word[] = { 'h', 'e', 'l', 'l', 'o', 0 };

stores the string "hello" in the array variable word . The array size is taken from the size of the initializer, which is 6 (5 characters plus the 0 terminator). The zero-valued byte serves as a sentinel value for string handling functions like strlen , strcpy , strcat , and for arguments to printf and scanf that use the %s and %[ conversion specifiers.

By contrast,

char arr[] = { 'h', 'e', 'l', 'l', 'o' };

stores a sequence of character values, but since there's no terminating 0-valued byte, this sequence is not considered a string , and you would not want to use it as an argument to any string-handling function (since there's no terminator, the function has no way of knowing where the string ends and will wind up attempting to access memory outside of the array, which can lead to anything from garbage output to a crash).

Without seeing the contents of lab8.h , I'm going to speculate that the string type is a typedef for an array of char , something like

#define MAX_STRING_LENGTH 20 // or some other value
typedef char string[MAX_STRING_LENGTH];

Thus, an array of string is an array of arrays of char ; it would be equivalent to

char words[MAX_COUNT][MAX_STRING_LENGTH];

So each words[i] is an N-element array of char .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM