Char指针改变另一个char指针? [英] Char pointer changes another char pointer?

查看:88
本文介绍了Char指针改变另一个char指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我的c程序有问题。



Hi all,
I have problem with my c program.

//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





如上所示Path []是一个字符串数组(char *),第一个项目有主目录路径(程序扫描根目录和子目录中的文件)。

问题是当p从(j:\d)变为(j:\\\\)时(在if语句中).. Path [x]的变化与p完全相同? ??

为什么??



为什么当char指针改变时,它会改变另一个char指针???



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???

推荐答案

目前尚不清楚你要做什么,但我认为你过分简化了你的代码(我相信strcpy(x,x)可能是未定义的行为?或者它只是检查一个有效的可写缓冲区?还是更新L1 / L2 / L3缓存?)。



看起来你正在尝试确保目录规范有一个终止''\\ \\''字符,然后您将文件名附加到目录规范。 2 strcpy()调用不会对您在此处提供的代码执行任何有效操作。 strcat()调用为2个附加操作执行繁重的操作。 2个指针''p''和''Filename''是''Path''缓冲区内的指针。如果您在p或文件名的末尾附加了某些内容,则还会附加到路径。它们都指向同一个缓冲区。
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.


你没有在第一行创建一个新的字符串...你正在分配数组的指针路径到字符指针 p (它们都指向相同的内存地址,我肯定你看看地址在调试器中你会注意到它是一样的。如果你想要一个具有相同值的新字符串,你必须做一个字符串拷贝(以及 p 的内存分配)。
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).


这篇关于Char指针改变另一个char指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆