C语言中使用指针遍历字符串数组时传入函数出现乱码的问题求助
C语言中使用指针遍历字符串数组时传入函数出现乱码的问题求助
我已经学C语言一个月了,现在卡在了当前的问题上。
我定义了一个字符串指针数组:
char **symbols; // An array of stock symbols for the set name
我用下面的函数来加载这个数组:
/* get_symbols - 11/02/2024 Retrieves the symbols for the set list from the database */ void get_symbols(void) { char *sql = concatenate(sql1, set_name, sql2); PGresult *r1 = PQexec(conn, sql); if (PQresultStatus(r1) != PGRES_TUPLES_OK) { printf("No data retrieved\n"); PQclear(r1); db_exit(conn); } symbol_count = PQntuples(r1); symbols = malloc(symbol_count * sizeof(char*)); if (symbols == NULL) { puts("Malloc error for symbols"); exit(2); } for (int i = 0; i < symbol_count; i++) *(symbols+i) = PQgetvalue(r1, i, 0); free(sql); PQclear(r1); }
我能正常遍历数组并在屏幕上打印每个股票代码:
/* Process each symbol */ for(int i = 0; i < symbol_count; i++) { /* Get the stock data */ // get_stock_data(*(symbols+i)); printf("%s\n", *(symbols+i)); }
(截图说明:执行这段代码时,所有股票代码都能正确打印到屏幕上)
但当我尝试调用函数加载每个股票代码对应的数据并展示时:
/* Process each symbol */ for(int i = 0; i < symbol_count; i++) { /* Get the stock data */ get_stock_data(*(symbols+i)); }
get_stock_data是负责获取并展示股票数据的函数:
/* get_stock_data - 11/04/2024 Gets the stock data from the database for a given symbol and fills the stock_data linked list. */ void get_stock_data(char *symbol) { char *sql = concat(sql3, symbol, sql4, begin_date, sql5, end_date, sql6); PGresult *r2 = PQexec(conn, sql); if (PQresultStatus(r2) != PGRES_TUPLES_OK) { printf("No data retrieved\n"); PQclear(r2); return; } int data_count = PQntuples(r2); printf("%d\n", data_count); for(int row = 0; row < data_count; row++) { for(int col = 0; col < 7; col++) printf("%s ", PQgetvalue(r2, row, col)); putchar('\n'); } free(sql); PQclear(r2); }
执行后,第一个股票代码的数据能正常展示,有时候第二个也能正常传入,但之后的股票代码就会变成乱码:
(截图说明:输出结果中前几个条目正常,后续出现大量无法识别的乱码字符)
我已经试过能想到的所有方法,但都没能解决问题。你能看出我的代码哪里有问题吗?提前谢谢了!
备注:内容来源于stack exchange,提问作者rollstreet
相关产品推荐
相关产品推荐

