0

I am writing in C, not C++ or C# How can open additional array inside a function and put 0 in all its elements in one line only?

at the moment i have errors

Error 1 error C2065: 'new' : undeclared identifier

Error 3 error C2143: syntax error : missing ';' before 'type'

Error 4 error C2143: syntax error : missing ';' before '['

all errors at the same place - at the declaration of the new array

void dup(int a[], int n)
{
    int i;
    int *t = new int[n]; 

    for(i=0; i<=n; i++)
        t[i] = 0;

    for(i=0;i<n;i++)
        t[a[i]]++;
}

3 Answers 3

4

Try using calloc in stdlib.h:

int *t = calloc(n, sizeof *t);
if (!t) {
    perror("calloc");
    return;
}
Sign up to request clarification or add additional context in comments.

Comments

3

new is a keyword specific to C++ and C#, and cannot be used in C.

Memory on the heap in C is primarily allocated via the function malloc and freed using the function free.

calloc is a version of malloc that also zeroes the memory before returning.

calloc take two arguments, the number of array elements and the size of each array element.

eg.

int i = 10;
int* p = calloc(i,sizeof(int));

http://www.cplusplus.com/reference/clibrary/cstdlib/calloc/

2 Comments

No, in C you shouldn't cast the result of malloc or calloc.
@KeithThompson Thanks. Never realised you didn't have to cast void pointers.
2

C doesn't have new, only C++.

Use calloc instead, found in <stdlib.h>

int *t = calloc(n, sizeof(int));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.