user1795374
user1795374

Reputation: 87

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

Upvotes: 0

Views: 3029

Answers (3)

Mike
Mike

Reputation: 49373

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

Upvotes: 0

Ritesh Kumar Gupta
Ritesh Kumar Gupta

Reputation: 5191

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

Upvotes: 0

mah
mah

Reputation: 39807

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

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

Upvotes: 1

Related Questions