简体   繁体   中英

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.

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. Creating a place to store the string:

char toDecrypt[] = node->string;

#2. Starting the for loop:

for(int m=0; m< strlen(toDecrypt); ++m)

#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...

Define your variable as char *toDecrypt = node->string;

You will still be able to use [] notation to read/write it if you wish.

This is wrong : char toDecrypt[] = node->string;

You can resolve it in following ways:

char *toDecrypt = node->string;

or

char *toDecrypt=(char*) malloc (strlen(node->string)+1);
strcpy(toDecrypt,node->string);
  • Creating a place to store the string:

You actually already have a place to store the string. node->string stores the string just fine. 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 :

toDecrypt[m] != '\\';

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