我将文本从编辑字段下载到缓冲区,并希望将其转换为字符串数组。每个字符串都以%结尾。
void Converter(HWND hwnd)
{
int Length = GetWindowTextLength(hEdit) + 1;
LPSTR data = (LPSTR)malloc(Length);
char set[500][11];
GetWindowTextA(hEdit, data, Length);
int x = 0, y = 0;
char record[10];
for (int i = 0; i < Length, x<500; i++)
{
if(data[i]!= '\0' )
{
record[y] = data[i];
y++;
}
else if(data[i] == '%')
{
strcpy(set[x], record);
x++;
y = 0;
}
}
free(data);
}我收到的错误消息:
Exception thrown at location 0x00007FF684C91F9B in myproject.exe: 0xC0000005: Access violation while reading at location 0x000000CBFC8D5DAF.发布于 2022-12-03 22:31:29
问题就在这条线上
for (int i = 0; i < Length, x<500; i++)你的情况不对,应该是:
for (int i = 0; i < Length && x<500; i++)此外,else if块永远不会执行,因为'%‘不等于'\0’。这可以通过交换它们来解决。
if(data[i] == '%')
{
strcpy(set[x], record);
x++;
y = 0;
}
else if(data[i] != '\0')
{
record[y] = data[i];
y++;
}第三个问题是,%分隔字符串中的最后一个单词不会复制到set中,因为后面没有百分比符号。
还有一只虫子。在复制之前,您忘记在记录的末尾放置一个空终止符,这会导致较短的字符串保留以前的字母。
record[y] = '\0';
strcpy(set[x], record);此时,我建议使用来自strtok的<string.h>和内存安全编程语言(如Rust )。
发布于 2022-12-03 22:52:37
使用用2d数组显示strcpy的示例代码:
#include <stdio.h>
int main() {
char set[500][11];
strcpy(&set[x][0], "a record");
printf(">> %s", &set[x][0]);
}输出:
>> a record发布于 2022-12-03 23:32:01
你可以这样做
char** make_array(_In_ char* buf, _Out_ unsigned* pn)
{
char* pc = buf;
unsigned n = 1;
while(pc = strchr(pc, '%')) n++, *pc++ = 0;
if (char** arr = new char*[n])
{
*pn = n;
char** ppc = arr;
do {
*ppc++ = buf;
buf += strlen(buf) + 1;
} while(--n);
return arr;
}
*pn = 0;
return 0;
}
void demo()
{
char buf[] = "1111%2222%33333";
unsigned n;
if (char** arr = make_array(buf, &n))
{
char** ppc = arr;
do {
printf("%s\n", *ppc++);
} while (--n);
delete [] arr;
}
}https://stackoverflow.com/questions/74671112
复制相似问题