In: Computer Science
I am trying to tokenize a string using a function by passing the char string[] and char *pointer[100]. While I have working code inside the int main(), I am having trouble actually declaring the parameters for the function.
I know how to pass the char array (char string[]), but not how to pass the char pointer array (char *pointer[100]).
This is my code below:
int main() {
// Declare variables
char str[] = "this is a test only - just a
test"; // char array
char *ptr1[100], *ptr2[100];
// Creates
two pointers
function1(str, *ptr1[100]);
return 0;
}
void function1(char str[], char *ptr1[100]) {
int i = 0;
int count = 0;
// Declaration of strtok: char
*strtok(char *str, const char *delim)
// It breaks *str into a series of
tokens using *delim
char *p = strtok (str, " ");
// Stores each piece into the
array
while (p != NULL) {
ptr1[i++] =
p;
p = strtok(NULL,
" ");
count++;
}
// Prints the array
for (i = 0; i < count; ++i)
{
printf("%s\n",
ptr1[i]);
}
}
For my code, it works if I get rid of the function and simply place the code in my int main(). Other times, I manipulated the second parameter and it started to work. However, the return values from 'p' transformed into integers from the "ptr1[i++] = p" portion of the code.
If you have any doubts, please give me comment...
#include <stdio.h>
#include <string.h>
void function1(char str[], char *ptr1[100]);
int main()
{
// Declare variables
char str[] = "this is a test only - just a test"; // char array
char *ptr1[100], *ptr2[100]; // Creates two pointers
function1(str, ptr1);
return 0;
}
void function1(char str[], char *ptr1[100])
{
int i = 0;
int count = 0;
// Declaration of strtok: char *strtok(char *str, const char *delim)
// It breaks *str into a series of tokens using *delim
char *p = strtok(str, " ");
// Stores each piece into the array
while (p != NULL)
{
ptr1[i++] = p;
p = strtok(NULL, " ");
count++;
}
// Prints the array
for (i = 0; i < count; ++i)
{
printf("%s\n", ptr1[i]);
}
}