I was trying to inverse a string in C. And I met some trouble defining the destination string.
And here are my thoughts: (I am a beginner, so my thoughts might seem laughable in your eyes...)
I define a string data type with unknown length and assign a string to it. (In my case it's str1)
I get the string length of string 1 and increment this value and assign to an integer. (l in my case. The +1 is to compensate the '\0' at the end of the string)
Use this l integer to define a new string which is the destination string. (str2 in my case.)
Use a for loop to copy from the end of str1 to the start of str2 and add a '\0' to the end of str2 to make it a string.
However, when I try to do this in visual studio 2013, it does not let me compile.
I have attached the error message and the code. (Line 15 in the error message is where I define str2 with integer l)
I tried to just put in a number (for example: 100) at the place where integer l was, and the code works.
Can you let me know what is wrong with defining a string with an integer variable and how to do it if there is a way in C, instead of just defining a long enough sting?
Thank you!
#include<stdio.h>
#include<string.h>
int main()
{
/* Reversing a string! */
int l; /* Length of str1 +1 (for the NULL character) */
char str1[] = "This is an unknown length string!";
l = strlen(str1) + 1;
char str2[l]; /* The destination string */
int i, j;
for (i = strlen(str1)-1,j=0; i < strlen(str1) && i >= 0; i--,j++)
str2[j] = str1[i];
str2[j] = '\0';
/* Display str1 and str2 */
printf("The content of str1: %s\n", str1);
printf("The content of str2: %s\n", str2);
return 0;
}
