[英]adding an int to a Multi-dimensional char Array
我試圖將int添加到多維char數組。 閱讀下面的鏈接后,我認為我可以使用sprintf。 如果我不能使用sprintf,那還有另一種方法呢?
http://www.cplusplus.com/reference/cstdio/sprintf/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char *argv[])
{
//{"TYPE", "ID", "SCOPE", "VALUE"}
char *symbol_table_variables[503][4];
int scope = 0;
int lower_bound_of_big_boy_counter = 0;
sprintf (symbol_table_variables[lower_bound_of_big_boy_counter][2], "%d", scope);
printf("symbol_table_variables[lower_bound_of_big_boy_counter][2] %s \n",
symbol_table_variables[lower_bound_of_big_boy_counter][2]);
return 0;
}
更新。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char *argv[])
{
//{"TYPE", "ID", "SCOPE", "VALUE"}
char *symbol_table_variables[503][4] = {0};
int scope = 5;
int lower_bound_of_big_boy_counter = 0;
char scope_char[80] = {0};
sprintf (scope_char, "%d", scope);
printf("scope_char %s \n", scope_char);
symbol_table_variables[lower_bound_of_big_boy_counter][2] =
malloc(strlen(scope_char)+1);
strcpy(symbol_table_variables[lower_bound_of_big_boy_counter][2],
scope_char);
memset(scope_char, 0, 80);
//sprintf (symbol_table_variables[lower_bound_of_big_boy_counter][2], "%d", scope);
printf("symbol_table_variables[lower_bound_of_big_boy_counter][2] is %s \n",
symbol_table_variables[lower_bound_of_big_boy_counter][2]);
return 0;
}
您正在調用未定義行為時, symbol_table_variables[lower_bound_of_big_boy_counter][2]
尚未分配任何內存。
一種解決方案是分配一些內存
symbol_table_variables[lower_bound_of_big_boy_counter][2] = malloc(32);
printf (symbol_table_variables[lower_bound_of_big_boy_counter][2], "%d", scope);
那不是很好,因為您並不真正知道需要多少內存。
我會質疑是否需要二維字符串數組...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.