Char array to char or char array to char?

So let's say I have a char, and I want strcat () to be a char array in one line of code. For a [non-practical] example:

strcat("ljsdflusdfg",getchar()); 

Or I wanted to do the opposite, what would be a suitable function for concat or typecast strings, regardless of the data type? Or maybe there is some kind of syntax that I am missing ...

Here is an example. It compiles just fine, but it crashes.

 char* input(){ char* inp=""; while(1){ char c=getchar(); if(c){ if(c=='\n'||c==EOF){ break; }else{ strcat(inp,(char*)c); } } } return inp; } 
+4
source share
8 answers

strcat treats its argument as a pointer to a null-terminated string. Throwing away a char in char * just dangerous, and I can’t imagine why it would never be useful (not implying that you are stupid for trying it), everyone makes stupid mistakes when they learn. here.)

The reason is that it will interpret a single char byte, plus the extra sizeof(char*) - sizeof(char) (usually 3) bytes surrounding this char , as a pointer that will point to ... anywhere. You have no way of knowing where it points, since 3 of these bytes are out of your control and therefore do not know if it points to reliable data.

You can use this as a second approach:

 strcat(inp, &c); 

This time you will be better, since &c is an expression of type char * , and no deviations are required. But then again, strcat assumes that the argument is a null-terminated string, and since you cannot guarantee a null byte after your char data, this will not happen.

The best way:

 size_t len = strlen(inp); // this may already be calculated somewhere else ... inp[len++] = c; // add c as the last character, and adjust our len inp[len] = '\0'; // add a new nul terminator to our string 

UPDATE:

Actually, I lied. The best way is to use the standard fgets library function, which seems to do more or less what you are trying to do. Honestly, I forgot about it, but if this is homework, your professor may not want you to use fgets so you can learn to do it manually. However, if this is not homework, fgets does exactly what you are looking for. (Actually, the third approach is well suited for overriding the functionality of fgets or fgets .)

I would also add some other comments to your input function:

  • char* inp = ""; will point to read-only data. A flaw in the C standard (for backward compatibility) allows you to assign string literals to char* types instead of const char * types, since it (IMHO) should be.

    There are several ways to approach this, but best of all is dynamic allocation. Use the malloc function to reserve some data, track how much you used in your function, and use the realloc function if you need more space to store it. If you need help with this, I am sure you will come back here (hopefully not soon) with another question. :)
  • getchar() returns int since EOF is defined outside the normal range of a char . To distinguish between any char and EOF , it is best to do c a int . Otherwise, a valid character may signal EOF . Be sure to add c to char if you add it to the string.
+3
source
 strcat(inp,(char*)c); 

This is an attempt to concatenate the contents of memory, where ever 'c' (as a memory location) until it finds zero.

It's best to create an empty string of any maximum size that you think is reasonable, fill it with zeros, and then just insert 'c' at the current last position

+2
source

If you want to combine one char into a string, you can use strncat() and specify the number of characters to combine as 1 . But note:

  • The destination buffer should have enough space; and
  • In C89, you must have an actual char object in order to accept the address (so you cannot directly concatenate the result of getchar() .

For instance:

 char str[5] = "foo"; char c; int ch; if ((ch = getchar()) != EOF) { c = ch; strncat(str, &c, 1); } 

In C99, you can use a composite literal, but the second restriction does not apply:

 char str[5] = "foo"; int ch; if ((ch = getchar()) != EOF) { strncat(str, &(char){ ch }, 1); } 
+2
source

This will not work because the * inp char pointer does not have memory backup. When you declared that it was char * inp = "; you only specified the address of the empty string. If you specified the following declaration char * inp =" abcdefg ", you could write 7 characters to it before overwriting '\ 0' and getting there in trouble.

You will need to dynamically increase the size of the backup memory as you type more characters. You will also have a problem finding out when to free memory so that you do not lose memory.

In addition, your strcat must have '&' before s.

+1
source

First, you return a pointer to the selected stack. This is undefined bahavior. Secondly, you are trying to write characters to unallocated memory. Third, the inp type is const char* not char* .

You need something like:

 char* input(char *dest) { strcpy(dest,""); while(1){ char c=getchar(); if(c){ if(c=='\n'||c==EOF){ break; }else{ strcat(inp,&c); } } } return dest; } 
0
source

Your code crashes because strcat expects a zero-terminated string for both parameters.

If you want to concatenate char, you first need to create a zero-terminated string from it.

 char c[2] = {0,0}; c[0] = getchar(); strcat(inp, c); 

But do not use strcat unless you can guarantee that the input string has allocated space for this extra character. Better you strncat, which also includes a parameter for the volume space in the first parameter (dest).

I recommend reading this first.

0
source

One easy way is to use snprintf:

 char newString[50+1]; snprintf(newString, sizeof(newString), "%s%c", "ljsdflusdfg", getchar()); 

This is a simple solution, but requires that you roughly know how large the string is, which will be ahead of time.

Notes: I use +1 to remind myself that there should be room for zero completion, and snprintf is better than sprintf, as it is set with a buffer size to prevent buffer overflows.

0
source

Insert char into char array?
This is the same as saying that you want to insert a char string into a string.
You simply cannot do this directly.
Instead of char, put it in an array (myChar []).
Afterwhich, strcat is with your original char array.

-1
source

Source: https://habr.com/ru/post/1335500/


All Articles