Click here to Skip to main content
15,880,364 members
Please Sign up or sign in to vote.
1.11/5 (2 votes)
See more:
Hi all,
I have problem with my c program.

C++
//I have reduced the code (x is a counter of loop)
char *p = Path[x]; //p have the next directory in the list
if(p[strlen(p) - 1] != '\\')
{
    strcpy(p,p);
    strcat(p,"\\");
}

char *FileName = p;
strcpy(FileName,FileName);
strcat(FileName,FindFileData.cFileName);

x++;
Path[x] = FileName; // add the directory to the list


As you see above Path[] is an array of string (char*) and the first item have primary directory path (the program is scanning files in root and sub directories).
The problem is when when p changes from ("j:\d") to ("j:\d\") (in if statement) .. Path[x] changes too exactly like p???
why??

why when char pointer changes, it changes the other char pointer???
Posted
Updated 4-Feb-13 19:37pm
v2

It is not clear what you are trying to do, but I think you oversimplified your code (also I believe strcpy(x, x) might be undefined behavior? or it just checks for a valid writeable buffer? or renews L1/L2/L3 cache?).

It looks like you are attempting to make sure that a directory spec has a terminating '\' character, then you append a filename to the directory spec. The 2 strcpy() calls don't do anything valid with the code as you present here. The strcat() calls do the heavy lifting for the 2 append operations. The 2 pointers 'p' and 'Filename' are pointers within the 'Path' buffer. If you append something to the end of either 'p' or 'Filename' you also append to 'Path'. They are all pointing within the same buffer space.
 
Share this answer
 
You're not creating a new string in your first line... you're assigning the pointer of the array Path to the character pointer p (they both point to the same memory address, I'm sure if you look at the addresses in a debugger you'll notice it's the same). If you want a new string that has the same value, you have to do a string copy (and a memory allocation for p).
 
Share this answer
 
v2
Comments
[no name] 5-Feb-13 5:37am    
Can you show me in code.
Albert Holguin 5-Feb-13 11:31am    
show you what in code? ...just google "C string copy" and I'm sure you'll get thousands of hits (if not more).
[no name] 6-Feb-13 1:55am    
Alright, thanx, I will google it and if I found the solution I will posted here.
Albert Holguin 6-Feb-13 10:56am    
If you have follow up questions, I'd be happy to help... but do a bit of research first.
fjdiewornncalwe 7-Feb-13 16:29pm    
My 5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900