Barbara88
Barbara88

Reputation: 277

declaration inside function syntax

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]]++;
}

Upvotes: 0

Views: 126

Answers (3)

Dunes
Dunes

Reputation: 40853

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/

Upvotes: 3

Pubby
Pubby

Reputation: 53097

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

Use calloc instead, found in <stdlib.h>

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

Upvotes: 2

cnicutar
cnicutar

Reputation: 182744

Try using calloc in stdlib.h:

int *t = calloc(n, sizeof *t);
if (!t) {
    perror("calloc");
    return;
}

Upvotes: 4

Related Questions