In addition to solution 1, some more errors:
1.
scanf
returns the number of items filled, which in your example is at best 1. If you want the length of the input string, check that
scanf
does return 1, then check the length of the string using
strlen()
.
2. You can't define a string on the stack with a variable length:
char strng2[k];
At the time of compilation, the value of k is not known, therefore the compiler will issue an error! If you want to reserve memory of just the right size, you must allocate that memory dynamically, on the heap, using
malloc
or
calloc
. Also, as pointed out above, you must use the correct length. And, in addition, you must add 1 to the length, because strings in C are terminated with a 0-Byte, and you must allocate memory for that byte as well!
3. you can't modify an array variable! You have actually managed to add several errors in just a few lines:
strng = strng + i;
a)
strng
is defined as an array. An array is a static range within memory. The location of that range is fixed and cannot be changed. Therefore the array variable cannot be changed. The compiler should issue at least one, possibly several error messages here!
b)
i
was never initialized. This line would produce undefined results, if it would even compile!
c) the following code modifies too many counters at once, as well as the starting address of the string you're looking at (if it would even work). I'm not going to bother to explain why your math is wrong, since it's based on erratic code anyway...
Hint: don't use any counters at all! Just use pointers to positions within the source and destination string (and do use separate pointer variables for that purpose)