Reputation: 152
I just started in C and this is a beginner question. But is there any way to copy a string without allocating memory beforehand?
I want to reproduce the strcopy function inbuilt in C with the same structure (char *strcpy(char *src, char *dest);
). I got it to work with declaring the char pointer in the function itself and then returning it. It works also with the original structure as strcpy if I allocate the memory beforehand.
#include <stdlib.h>
char *strcopy(char *src, char *dest)
{
int i = 0;
while (src[i] != '\0')
{
dest[i] = src[i];
i++;
}
dest[i] = '\0';
return (dest);
}
int str_size(char *str)
{
int i = 0;
while (str[i] != '\0')
i++;
return (i);
}
int main(int argc, char **argv)
{
char *src = argv[1];
char *dest = (char*)malloc(str_size(src));
dest = strcopy(src, dest);
return (0);
}
So is it somehow possible to copy a string without allocating memory beforehand and without changing my function-head?
Upvotes: 0
Views: 1368
Reputation: 2185
If you want to avoid dynamic allocation, use static allocation:
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 1024
char *strcopy(char *src, char *dest)
{
int i = 0;
while (src[i] != '\0')
{
dest[i] = src[i];
i++;
}
dest[i] = '\0';
return (dest);
}
int str_size(char *str)
{
int i = 0;
while (str[i] != '\0')
i++;
return (i);
}
int main(int argc, char **argv)
{
char *src = argv[1];
char dest[BUFFER_SIZE];
if(strlen(src) >= BUFFER_SIZE){
return -1;
}
else{
dest = strcopy(src, dest);
}
return 0;
}
Upvotes: 1