I am trying to take an array of char, pass it to a void function by point (mainly, I don't want that array to be copied), manipulate/add to it, and leave the function but with the array holding its new information in main().
I understand that I could just use strcpy or some other function, but there will be text processing involved in the function that strcpy won't do. Also, I'd just like to learn the proper way of passing a string to a function and changing it.
Here is what I have so far:
Code:
/*
gcc -Wall -O3 fast.c -o fast
*/
#include<stdio.h> // printf
#include<stdlib.h> // malloc, free
void fast_strcatSp(char *str, const char *strCat)
{
// Lots to be done in here but keeping it simple for this question
size_t pos = 0;
while(strCat[pos] != '\0')
{
str[pos] = strCat[pos];
++pos;
}
str[pos + 1] = '\0';
printf("Function str: %s\n", str);
}
#define STRSIZE 100
int main() {
char * str[STRSIZE];
char addToStr[10] = "abcdef";
fast_strcatSp(&str, addToStr);
printf("Returned text: %s\n", str);
return 0;
}
The compiler complains:
Code:
fast.c: In function ‘main’:
fast.c:164:19: warning: passing argument 1 of ‘fast_strcatSp’ from incompatible pointer type [-Wincompatible-pointer-types]
fast_strcatSp(&myStr, addToStr);
^
fast.c:138:6: note: expected ‘char *’ but argument is of type ‘char * (*)[100]’
void fast_strcatSp(char *str, const char *strCat)
^~~~~~~~~~~~~
fast.c:166:29: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char **’ [-Wformat=]
printf("Returned text: %s\n", myStr);
^
It succeeds, though, and prints:
Code:
Function str: abcdef
Returned text: abcdef
At least the string made it back to main, but I'd like to take care of those warnings.