Reputation: 3064
I know this question might sound quite silly, but I somehow found myself stuck and need help. I have a char*
variable char* address="/a/asdasd/c/sdfsdf/adsd";
and I declared an array of char pointer char* store[5];
. I'm trying to divide the content in the variable address
by tracing the slash(/
) and trying to store each part in the char pointer variable store
by doing the following
char* store[5];
char* address="/a/asdasd/c/sdfsdf/adsd";
int k=0;
int j=0;
char* b=NULL;
for(int i=0;i<5;i++)
{
if(b==0)
{
b=strchr(address,'/');
}
else
{
b=strchr(b,'/');
}
j=b-address;
strncpy(store[i],address+k,j-k);
k=j;
}
But I see that in the code strncpy(store[i],address+k,j-k)
there's an error. The compiler doesn't seem to understand that store[i]
is a char pointer, it rather thinks it is a char. Could you see how I can solve the problem?
Thanks for all the help. I've solved it. Solution code is as below:
char* address="/a/asdasd/c/sdfsdf/adsd/asfsd";
char store[5][100];
char* b=NULL;
int k=0;
int j=0;
for(int i=0;i<5;i++)
{
if(b==0)
{
b=strchr(address+1,'/');
}
else
{
b=strchr(b+1,'/');
}
j=strlen(address)-strlen(b);
strncpy(store[i],address+k+1,j-k-1);
store[i][j-k-1]='\0';
printf("%s\n",store[i],j-k);
k=j;
}
Upvotes: 0
Views: 2436
Reputation: 14408
If you don't want to have a copy of the string tokens, if you like only to retain the pointers, then just store the address in store[i] as @unwind pointed out. Or else, you could explore strtok () also. only think is that you need to have separate array to keep each length of the string according to your code. Hope this helps.
Upvotes: 0
Reputation: 399703
If you want to copy a pointer, you shouldn't be calling strncpy()
, since that copies characters.
You want:
store[i] = address + (j - k);
assuming address + (j - k)
is the desired starting point for the part.
Upvotes: 1
Reputation: 24895
char *store[5]
This is just an array of char pointers. To store strings in each element of this array, you need malloc memory and assign it to the respective pointer.
For Ex, you can change your code to
store[i] = malloc ((j-k)+ 1); // +1 is for the null terminator. Pls check return value of malloc also.
strncpy(store[i],address+k,j-k);
Upvotes: 3