Task: Write a function that takes as parameter a string, an array of pointers and its length and fills the array with addresses to the beginning of each (whitespace-separated) word in the string (similar to the argv[] array of main). Terminate the array with a NULL pointer after the last valid address.
I have some questions. 'An array of pointers' = array of addresses (correct me if I'm wrong I'm learning pointers). From what I know an address is a huge number, so how can I store the addresses of the words in the array, without overflowing it?
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void wordAdresses(char *s, int *ptr_arr, int cap)
{
ptr_arr[0] = '\0';
cap = 1;
char* word = strtok(s, " ");
while(word != NULL)
{
int address = *word;
ptr_arr[cap] = *word;
cap++;
if(address+1 > cap)
{
printf("String overflow\n");
}
cap -= address;
//printf("Word is %s <--> Value is %X\n",word, word);
word = strtok(NULL, " ");
}
for(int i = 0; i < cap; i++)
{
printf("%d\n", ptr_arr[i]);
}
}
int main()
{
char s[] = "john goes to school";
int ptr_arr[100];
wordAdresses(s, ptr_arr, sizeof ptr_arr);
return 0;
}
Output:
String overflow
String overflow
String overflow
String overflow
Now if I put the last for between comments and remove them for the second printf
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void wordAdresses(char *s, int *ptr_arr, int cap)
{
ptr_arr[0] = '\0';
cap = 1;
char* word = strtok(s, " ");
while(word != NULL)
{
int address = *word;
ptr_arr[cap] = *word;
cap++;
if(address+1 > cap)
{
printf("String overflow\n");
}
cap -= address;
printf("Word is %s <--> Value is %X\n",word, word);
word = strtok(NULL, " ");
}
/* for(int i = 0; i < cap; i++)
{
printf("%d\n", ptr_arr[i]);
}*/
}
int main()
{
char s[] = "john goes to school";
int ptr_arr[100];
wordAdresses(s, ptr_arr, sizeof ptr_arr);
return 0;
}
Output:
String overflow
Word is john <--> Value is 61FE00
String overflow
Word is goes <--> Value is 61FE05
String overflow
Word is to <--> Value is 61FE0A
String overflow
Word is school <--> Value is 61FE0D
So I get the adress of the beginning of each word, but also the message "String overflow" because the numbers are huge. So how can I put the addresses into the array and avoid overflowing?