gpt4 book ai didi

c - 基于 C 中用户输入的动态增长数组

转载 作者:太空宇宙 更新时间:2023-11-04 07:47:01 25 4
gpt4 key购买 nike

我需要创建一个程序:

  1. initially allocate an array to read in and hold up to 5 temperatures.
  2. prompt the user to enter temperatures and type the value -100.0 when they are finished
  3. if the user fills up the array your program should dynamically allocate a new array which is double the size.
  4. copy the old values across to the new array. deallocate the old array.
  5. continue reading into the new array.
  6. print the new array out when it's done

我是 C 语言的新手,有点卡住了。我知道如何创建一个动态数组,但我不知道如何创建一个新数组,一旦旧数组填满,它就会不断增长。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void){
int i,k; //loop count
int j = 5; //initial array size
int* temp = malloc(sizeof(int)*j);
int* newtemp;

for (i = 0; i < j; i++){ //loop to read in temperature
printf("enter temperature: ");
scanf("%d",(temp+i));
if (i=j){
j = j*2; //double the size of initial array
int* newtemp = malloc(sizeof(int)*j);
strcpy(*newtemp,temp); // copy string
for (k = 0; k < j; k++){ //loop to read in temperature
printf("enter temperature: ");
scanf("%d",(temp+i+k));
}
}
switch (temp[i]){
case (-100):
temp[i] = '\0';
i = 5; //loop ends
break;
}
}
return 0;
}

错误信息:

tempp.c:18:16: warning: passing argument 1 of ‘strcpy’ makes pointer from integer without a cast [-Wint-conversion]
strcpy(*newtemp,temp);
^
In file included from tempp.c:3:0:
/usr/include/string.h:121:14: note: expected ‘char * restrict’ but argument is of type ‘int’
extern char *strcpy (char *__restrict __dest, const char *__restrict __src)
^~~~~~
tempp.c:18:25: warning: passing argument 2 of ‘strcpy’ from incompatible pointer type [-Wincompatible-pointer-types]
strcpy(*newtemp,temp);
^~~~
In file included from tempp.c:3:0:
/usr/include/string.h:121:14: note: expected ‘const char * restrict’ but argument is of type ‘int *’
extern char *strcpy (char *__restrict __dest, const char *__restrict __src)

我知道我的代码很乱,而且我真的不知道在新数组不断增长时重新分配它的正确方法。请在这件事上给予我帮助。谢谢!

最佳答案

改用 realloc 工具如何?

void printArray(double *array, int size){
for(int i=0; i<size; i++){
printf("%.1lf ", array[i]);
}
putchar('\n');
}

int main(void){
int size = 5;
double *array = malloc(size * sizeof(double));
double temperature;
int i = 0;

while(1){
if(temperature == -100.0)
break;
if(i == size){
size *= 2;
array = realloc(array, size * sizeof(double));
}
scanf("%lf", &temperature);
array[i] = temperature;
printArray(array, size);
i++;
}
free(array);
return 0;
}

关于c - 基于 C 中用户输入的动态增长数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56254128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com