0

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

2
  • #2: you are evaluating the length of the string for each iteration in the 'for' loop -- I would rather use for (int m = 0, int L = strlen(toDecrypt); m < L; m++) Commented Apr 1, 2013 at 18:29
  • 2
    Escape the backslash, '\\'. Commented Apr 1, 2013 at 18:40

3 Answers 3

1

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

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

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

0
  • 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] != '\\';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.