I downloaded text from edit field to buffer and i want to convert it to a array of strings. Every string is ending with "%".
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);
}
The error message i get is this:
Exception thrown at location 0x00007FF684C91F9B in myproject.exe: 0xC0000005: Access violation while reading at location 0x000000CBFC8D5DAF.
Please be easy on me
CodePudding user response:
The problem is in this line
for (int i = 0; i < Length, x<500; i )
Your condition is wrong, it should be:
for (int i = 0; i < Length && x<500; i )
Also, the else if
block is never executed, because '%' is not equal to '\0'. This can be fixed by swapping them.
if(data[i] == '%')
{
strcpy(set[x], record);
x ;
y = 0;
}
else if(data[i] != '\0')
{
record[y] = data[i];
y ;
}
The third problem is that the last word in your %-delimited string will not be copied into set
since there is no percent sign after it.
There is one more bug. You forgot to put a null-terminator at the end of record before copying it, this causes shorter strings to retain letters from previous ones.
record[y] = '\0';
strcpy(set[x], record);
At this point I recommend using strtok
from <string.h>
, and a memory safe programming language like Rust, because C is too dangerous in your hands.
CodePudding user response:
Sample code to show strcpy with 2d array is use:
#include <stdio.h>
int main() {
char set[500][11];
strcpy(&set[x][0], "a record");
printf(">> %s", &set[x][0]);
}
Output:
>> a record
CodePudding user response:
you can do like this
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"223333";
unsigned n;
if (char** arr = make_array(buf, &n))
{
char** ppc = arr;
do {
printf("%s\n", *ppc );
} while (--n);
delete [] arr;
}
}