简体   繁体   中英

C - How do I attach ASCII-Code to char array

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

if you know the ascii code, why not write it directly?

line[i] = 196;

Will this work?

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.

  • In line #1, you are just declaring char array and not initializing it. So it can contain anything. So your strcat in line#2 can start from outside the array also if there is no '\\0' character in the allocated array. So better initialize it - char line[50] = "" ;
  • Regarding line#2 and line#3: If you want continuous charaqcter-196, you can do one of the following - for(..,i < MAX-1,..) line[i]=196; line[i+1]='\\0'; 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*/);

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'; char dummy[2]; dummy[0] = 196; dummy[1] = '\\0'; and then strcat(line,dummy);

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