复制数组并修改其元素的函数

时间:2018-11-17 11:35:45

标签: c arrays

要求我定义一个带有三个参数的函数array_ncopy()

  • int *ptr表示一个指向整数数组的指针

  • int array表示数组的大小

  • int n代表一个整数

,并将*ptr指向的数组元素复制到另一个列表。但是,所有索引大于NUMBER的元素都将被复制为0

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#define NUMBER 12
#define MAX  100
#define SIZE  8

void array_print(int *ptr, int array) {
    for (int i = 0; i < array; i++){
        printf("Value of array[%d] is %d",i, ptr[i]);
        printf("\n");
    }
}

int* array_create(int array) {
    int *t = malloc(array * sizeof(int));
    for (int i = 0; i < array; i++) {
        t[i] = rand() % MAX;
    }

    return t;
}

int* array_ncopy(int *ptr, int array, int n) {
    for (int i=0; i < n; i++){
        if (i >= n) {
            ptr[i] = 0;
        }
        ptr[i] = ptr[i];
    }
    return ptr;
}

int main() {
  int *t = array_create(SIZE);
  int *ptr = array_ncopy(t, SIZE, NUMBER);
  array_print(ptr, NUMBER);
  free(t);
  free(ptr);
  return 0;
}

以这个数组为例:

{23, 7, 4, 32, 55, 2, 78, 26}

我应该得到这个结果:

对于NUMBER = 4:

Value of array[0] is 83
Value of array[1] is 86
Value of array[2] is 77
Value of array[3] is 15

对于NUMBER = 12:

Value of array[0] is 83
Value of array[1] is 86
Value of array[2] is 77
Value of array[3] is 15
Value of array[4] is 93
Value of array[5] is 35
Value of array[6] is 86
Value of array[7] is 92
Value of array[8] is 0
Value of array[9] is 0
Value of array[10] is 0
Value of array[11] is 0

相反,我得到以下输出:

NUMBER = 12

Value of array[0] is 83
Value of array[1] is 86
Value of array[2] is 77
Value of array[3] is 15
Value of array[4] is 93
Value of array[5] is 35
Value of array[6] is 86
Value of array[7] is 92
Value of array[8] is 0
Value of array[9] is 0
Value of array[10] is 4113
Value of array[11] is 0

有人可以更正我的代码,以便输出正确的内容。

5 个答案:

答案 0 :(得分:0)

这是针对编译器的警告:

++ clang -Wall -Wextra -std=c11 -pedantic-errors prg.c
prg.c:23:32: warning: unused parameter 'array' [-Wunused-parameter]
int* array_ncopy(int *ptr, int array, int n) {
                               ^
1 warning generated.

您根本没有使用变量数组。做:

for (int i=0; i < array; i++){

答案 1 :(得分:0)

由于存在一些非常令人困惑的,有时甚至是错误的事情,因此我将尝试逐一进行研究,以使其更加清晰。

#define NUMBER 12 
#define MAX  100
#define SIZE 8

此处为NUMBER> SIZE;这意味着您的数组将永远无法达到upper_bound。

    int* array_ncopy(int *ptr, int array, int n)
 {
    for (int i = 0; i < n; i++) 
        if (i >= n) {
            ptr[i] = 0;
        }
        ptr[i] = ptr[i];
    }
    return ptr;
}

for(int i = 0; i < n; i++)-在这里循环直到n(上限),而不是达到数组大小。

ptr[i] = ptr[i];不会将值复制到另一个数组,而只是将值再次分配给同一数组。相反,您必须创建一个数组int *cpy = (int*)malloc(length * sizeof(int));,然后按如下所示为其分配值:

    int* array_ncopy(int *ptr, int length, int upperBound) // ptr = first array
    {    
int *cpy = (int*)malloc(length * sizeof(int)); // create copy array
        for (int i = 0; i < length; i++)
        {
            if (i >= upperBound) 
                cpy[i] = 0; 
            else
            cpy[i] = ptr[i]; // copy to array if i < upperBound
        }
        return cpy;
    }

除此之外:

在几乎所有函数声明中,您的命名方案都还不清楚(名称很好,但是您的变量名可能更具描述性)。 乍看之下,很难真正知道int* array_ncopy(int *ptr, int array, int n)数组是什么(因为它是int而不是ptr),或者n在这里意味着什么。所以我建议将其更改为array_ncopy(int *ptr, int length, int upperBound)

下面您可以通过一种更加惯用的方式找到您的程序(并且可以正常工作)

#include <stdio.h>
    #include <stdlib.h>
    #define UPPER_BOUND 8
    #define MAX  100
    #define SIZE  12

void array_print(int *ptr, int length) {
    for (int i = 0; i < length; i++) {
        printf("Value of array[%d] is %d", i, ptr[i]);
        printf("\n");
    }
}

int* array_create(int length) {
    int *t = (int*)malloc(length * sizeof(int));
    for (int i = 0; i < length; i++) {
        t[i] = rand() % MAX;
    }

    return t;
}

    int* array_ncopy(int *ptr, int length, int upperBound)
    {    
int *cpy = (int*)malloc(length * sizeof(int));
        for (int i = 0; i < length; i++)
        {
            if (i >= upperBound)
                cpy[i] = 0;
            else
            cpy[i] = ptr[i];
        }
        return cpy;
    }

    int main()
 {
    int *t = array_create(SIZE);
    int *cpy = array_ncopy(t, SIZE, UPPER_BOUND);
    array_print(cpy, SIZE);
    free(t);
    free(cpy);
    return 0;
}

答案 2 :(得分:0)

根据规范,复制功能应为:

int* array_ncopy(int *ptr, int array, int number)
{
    int *new_array= malloc(array*sizeof(int));
    for (int i=0; i < array; i++){
        if (i >= number) {
            new_array[i] = 0;
        }
        else new_array[i] = ptr[i];
    }
    return new_array;
}

这会将元素复制到新数组(指定)。数组大小与旧数组的大小相同(隐式指定)。复制旧数组中索引为<= number的所有元素,并将大于此元素的元素设置为零。如果number >= array,则没有元素设置为零(隐式指定)。

答案 3 :(得分:0)

另一种方法:

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'yyy.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets
#from PyQt5.QtCore import pyqtSlot, pyqtSignal

class Ui_MainWindow(object):

#    ClickAction = pyqtSignal(QtWidgets.QMainWindow)

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        MainWindow.setStyleSheet("gridline-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(0, 0, 0, 255), stop:1 rgba(255, 255, 255, 255));")
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.horizontalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
        self.horizontalLayoutWidget.setGeometry(QtCore.QRect(0, 0, 191, 551))
        self.horizontalLayoutWidget.setObjectName("horizontalLayoutWidget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget)
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.treeWidget = QtWidgets.QTreeWidget(self.horizontalLayoutWidget)
        self.treeWidget.setAnimated(True)
        self.treeWidget.setObjectName("treeWidget")
        self.horizontalLayout.addWidget(self.treeWidget)
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(470, 150, 75, 23))
        self.pushButton.setObjectName("pushButton")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(310, 110, 411, 20))
        self.lineEdit.setObjectName("lineEdit")
        self.plainTextEdit = QtWidgets.QPlainTextEdit(self.centralwidget)
        self.plainTextEdit.setGeometry(QtCore.QRect(310, 210, 431, 91))
        self.plainTextEdit.setObjectName("plainTextEdit")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
        self.menubar.setObjectName("menubar")
        self.menuFile = QtWidgets.QMenu(self.menubar)
        self.menuFile.setObjectName("menuFile")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.actionNew = QtWidgets.QAction(MainWindow)
        self.actionNew.setObjectName("actionNew")
        self.actionOpen = QtWidgets.QAction(MainWindow)
        self.actionOpen.setObjectName("actionOpen")
        self.actionClose = QtWidgets.QAction(MainWindow)
        self.actionClose.setObjectName("actionClose")
        self.actionExit = QtWidgets.QAction(MainWindow)
        self.actionExit.setObjectName("actionExit")
        self.menuFile.addAction(self.actionNew)
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionOpen)
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionClose)
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionExit)
        self.menubar.addAction(self.menuFile.menuAction())
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)


    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.treeWidget.headerItem().setText(0, _translate("MainWindow", "1"))
        self.treeWidget.headerItem().setText(1, _translate("MainWindow", "New Column"))
        self.treeWidget.headerItem().setText(2, _translate("MainWindow", "New Column"))
        self.treeWidget.headerItem().setText(3, _translate("MainWindow", "New Column"))
        self.treeWidget.headerItem().setText(4, _translate("MainWindow", "New Column"))
        self.pushButton.setText(_translate("MainWindow", "PushButton"))
        self.menuFile.setTitle(_translate("MainWindow", "File"))
        self.actionNew.setText(_translate("MainWindow", "New"))
        self.actionOpen.setText(_translate("MainWindow", "Open"))
        self.actionClose.setText(_translate("MainWindow", "Close"))
        self.actionExit.setText(_translate("MainWindow", "Exit"))

#        self.pushButton.clicked.connect(self.On_ClickAction)
#    def On_ClickAction(self):
#        self.ClickAction.emit("self.lineEdit.text")

此外,使用带符号的int *array_ncopy(int *ptr, unsigned int size, unsigned int number) { // create a zero-filled array the same size int *newArray = calloc( size, sizeof( *newArray ) ); // error checking - ALWAYS do error checking! if ( !newArray ) { return( NULL ); } // copy the first "number" elements to the new array // making sure to limit the max amount copied number = MIN( number, size ); memcpy( newArray, ptr, number * sizeof( *newArray ) ); return( newArray ); } 表示数组中元素的数量是荒谬的,并且可能导致一些奇怪的错误。

答案 4 :(得分:-1)

尝试这个

int* array_ncopy(int *ptr, int array, int n) {
    for (int i=0; i < array; i++){
        if (i >= n) {
            ptr[i] = 0;
        }
        ptr[i] = ptr[i];
    }
    return ptr;
}

祝你好运