[英]How do I iterate through a pointer to a char array in C?
I'm new to C, and I'm having a bit of trouble figuring out the exact way to do this. 我是C语言的新手,在弄清楚执行此操作的确切方法时遇到了一些麻烦。
I need to iterate through a string and store each letter one at a time in order to decrypt it. 我需要遍历一个字符串并一次将每个字母存储一个,以便对其进行解密。
So what I'm doing is: 所以我正在做的是:
#1. #1 Creating a place to store the string:
创建一个存储字符串的地方:
char toDecrypt[] = node->string;
#2. #2。 Starting the for loop:
启动for循环:
for(int m=0; m< strlen(toDecrypt); ++m)
#3. #3。 Storing the char (to be decrypted later):
存储字符(稍后将解密):
char i = toDecrypt[m];
So is the above valid, or should I be using a different notation to properly store the char? 那么以上方法是否有效,还是应该使用其他符号正确存储字符?
EDIT: 编辑:
Ok, I think I have that cleared up, so I just have one follow up question. 好的,我想我已经解决了这个问题,所以我只有一个后续问题。
How do I check to see if a char is a "\\"? 如何检查字符是否为“ \\”? My check doesn't seem to be working.
我的支票似乎无效。
When I put 当我放
toDecrypt[m] != '\';
into an if statement, it doesn't work... 变成if语句,那是行不通的...
Define your variable as char *toDecrypt = node->string;
将变量定义为
char *toDecrypt = node->string;
You will still be able to use []
notation to read/write it if you wish. 如果愿意,您仍然可以使用
[]
表示法进行读取/写入。
- Creating a place to store the string:
创建一个存储字符串的地方:
You actually already have a place to store the string. 您实际上已经有一个存储字符串的地方。
node->string
stores the string just fine. node->string
存储字符串就好了。 You can just create a pointer to point to it: 您可以创建一个指向它的指针:
char *toDecrypt = node->string;
or if you want someplace to copy it you can make an array: 或者,如果您想复制某个地方,可以制作一个数组:
char toDecrypt[enough_space_for_the_string];
// or do it dynamically with:
// char * toDecrypt = malloc(enough_space_for_the_string);
// just don't forget to free() it later
strcpy(toDecrypt, node->string);
- How do I check to see if a char is a "\\"?
如何检查字符是否为“ \\”? My check doesn't seem to be working.
我的支票似乎无效。
The backslash is an escape character in C so if you want to check for a backslash you need to use the correct escape sequence : 反斜杠是C语言中的转义字符,因此,如果要检查反斜杠,则需要使用正确的转义序列 :
toDecrypt[m] != '\\';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.