Reputation: 357
I'm still new to programming but lets say I have a two dimensional char
array with one letter in each array. Now I'm trying to combine each of these letters in the array into one array to create a word.
So grid[2][4]
:
0|1|2|3
0 g|o|o|d
1 o|d|d|s
And copy grid[0][0]
, grid[0][1]
, grid[0][2]
, grid[0][3]
into a single array destination[4]
so it reads 'good'. I have something like
char destination[4];
strcpy(destination, grid[0][1]);
for(i=0; i<4; i++)
strcat(destination, grid[0][i]);
but it simply crashes..
Any step in the right direction is appreciated.
Upvotes: 1
Views: 1708
Reputation: 1759
In C, the runtime library functions strcpy
and strcat
require zero terminated strings. What you're handing to them are not zero terminated, and so these functions will crash due to their dependency on that terminating zero to indicate when they should stop. They are running through RAM until they read a zero, which could be anywhere in RAM, including protected RAM outside your program, causing a crash. In modern work we consider functions like strcpy and strcat to be unsafe. Any kind of mistake in handing them pointers causes this problem.
Versions of strcpy and strcat exist, with slightly different names, which require an integer or size_t indicating their maximum valid size. strncat
, for example, has the signature:
char * strncat( char *destination, const char *source, size_t num );
If, in your case, you had used strncat, providing 4 for the last parameter, it would not have crashed.
However, an alternative exists you may prefer to explore. You can simply use indexing, as in:
char destination[5]; // I like room for a zero terminator here
for(i=0; i<4; i++)
destination[i] = grid[0][i];
This does not handle the zero terminator, which you might append with:
destination[4] = 0;
Now, let's assume you wanted to continue, putting both words into a single output string. You might do:
char destination[10]; // I like room for a zero terminator here
int d=0;
for(r=0; r<2; ++r ) // I prefer the habit of prefix instead of postfix
{
for( i=0; i<4; ++i )
destination[d++] = grid[r][i];
destination[d++] = ' ';// append a space between words
}
Following whatever processing is required on what might be an ever larger declaration for destination, append a zero terminator with
destination[ d ] = 0;
Upvotes: 4
Reputation: 15861
strcpy
copies strings, not chars. A string in C is a series of chars, followed by a \0
. These are called "null-terminated" strings. So your calls to strcpy
and strcat
aren't giving them the right kind of parameters.
strcpy
copies character after character until it hits a \0
; it doesn't just copy the one char you're giving it a pointer to.
If you want to copy a character, can just assign it.
char destination[5];
for(i = 0; i < 4; i++)
destination[i] = grid[0][i];
destination[i] = '\0';
Upvotes: 2