Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create array of fixed-length "strings" in C?

I am trying to create an array of fixed-length "strings" in C, but have been having a little trouble. The problem I am having is that I am getting a segmentation fault.

Here is the objective of my program: I would like to set the array's strings by index using data read from a text file. Here is the gists of my current code (I apologize that I couldn't add my entire code, but it is quite lengthy, and would likely just cause confusion):

//"n" is set at run time, and 256 is the length I would like the individual strings to be
char (*stringArray[n])[256];
char currentString[256];

//"inputFile" is a pointer to a FILE object (a .txt file)
fread(&currentString, 256, 1, inputFile);
//I would like to set the string at index 0 to the data that was just read in from the inputFile
strcpy(stringArray[i], &currentString);
like image 817
user3495690 Avatar asked Nov 07 '15 21:11

user3495690


Video Answer


1 Answers

Note that if your string can be 256 characters long, you need its container to be 257 bytes long, in order to add the final \0 null character.

typedef char FixedLengthString[257];
FixedLengthString stringArray[N];
FixedLengthString currentString;

The rest of the code should behave the same, although some casting might be necessary to please functions expecting char* or const char* instead of FixedLengthString (which can be considered a different type depending on compiler flags).

like image 85
Cyan Avatar answered Sep 18 '22 23:09

Cyan