Reputation: 61
I have to make a char array out of many strings/ASCII-Code. While adding strings works fine, adding ASCII-Code does not.
char line[50];
strcat(line, " "); // works
for (int i = 0; i < 29; i++) strcat(line, '196'); // supposed to add lines
for (int i = 0; i < 29; i++) strcat(line, 196);
Neither of these work. I always get this error message(had to translate it).
Exception at 0x00E620E7 in the test.exe: 0xC0000005: Access Violation While Reading a Location 0x00313936.
What am I missing? Thanks for your help
Upvotes: 1
Views: 2077
Reputation: 1947
In C, String is written between double quotes.
Example "abc"
is a string.
To strcat()
, you are suppose to pass dst and str pointers which are pointing to a string.
In the line #2, you are correctly using strcat()
. line is pointer to char array, and " "
is pointer to a string literal.
But in line #3, '196'
is not a string. If you want to write 196 to string, it should be strcat(line, "196");
Same goes for line #4.
Please note the following.
char line[50] = ""
;for(..,i < MAX-1,..) line[i]=196; line[i+1]='\0';
OR for(..,i < MAX-1,..) strcat(line, "_"/* Assuming this is the character for 196*/);
Upvotes: 1
Reputation: 685
if you know the ascii code, why not write it directly?
line[i] = 196;
Will this work?
Upvotes: 1
Reputation: 6395
196
is a char
(or an int
), not a string, and it is not a valid parameter for strcat
(which means 'string concatenation'). '196'
is nothing valid at all and will not compile.
Strings are sequences of chars that end with a '\0'
. If you want to append a single char, you have to either handle it manually (by directly assigning it, for example line[i] = 196;
), or you have to use a _dummy helper string_with two chars, like: char dummy[2]; dummy[0] = 196; dummy[1] = '\0';
and then strcat(line,dummy);
Upvotes: 0