我在为数组动态分配内存时遇到问题。 该程序只是应该将第一行与第二行交换,将第三行与第四行交换。我得到了奇怪的结果,例如:
输入字符串:你好
输入字符串:你好吗
输入字符串:我很好,谢谢
输入字符串:再见
输入字符串:bai
输入字符串:xx
==========================
你好吗
!我很好,谢谢
你好
!你好吗
再见
!拜
我很好,谢谢
!再见
拜
!xx
int count = 0;
char *lines[MAX_LINES];
char *tmp[50];
printf("Enter string: ");
fgets(tmp, 50, stdin);
lines[count] = (char *) malloc((strlen(tmp)+1) * sizeof(char));
strcpy(lines[count], tmp);
while(strcmp("xx\n", lines[count])){
count++;
printf("Enter string: ");
fgets(tmp, 50, stdin);
lines[count] = (char *) malloc((strlen(tmp)+1)* sizeof(char));
strcpy(lines[count], tmp);
}
void exchange(char * records[])
{
char * temp;
temp = records[0];
records[0] = records[1];
records[1] = temp;
temp = records[2];
records[2] = records[3];
records[3] = temp;
}
void printArray(char * inputs[], int row, int col)
{
int i, j;
for(i = 0; i < row; i++){
for(j = 0; j < col; j++){
printf("%c", inputs[i][j]);
}
}
}
最佳答案
这不好:
char *tmp[50];
您打算这样做:
char tmp[50];
奇怪的是,它会有点工作,但你的编译器应该到处抛出警告。
我认为你的主要问题是你的 printArray 函数,它不检查字符串中的 NULL 终止符。所以它会在大多数的末尾运行。
不要逐个字符地打印,而是这样做:
void printArray(char * inputs[], int length)
{
int i;
for(i = 0; i < length; i++){
printf("%s", inputs[i]);
}
}
这里有一个关于使用 malloc
的提示。不要强制转换结果,如果您要为 char
值保留空间,请不要使用 sizeof(char)
- 它始终为 1。
lines[count] = malloc( strlen(tmp) + 1 );
关于c - 使用临时数组的动态内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17459597/