C언어 질문입니다!! (calloc, 오류찾기..)

C언어 질문입니다!! (calloc, 오류찾기..)

작성일 2021.02.02댓글 1건
    게시물 수정 , 삭제는 로그인 필요

주석으로 코드에 맞는 문제를 줍니다.


/* repeat.c - repeat a given string n times

 * Compile with CFLAGS="-pedantic –std=c11" make repeat

 * Use with e.g. ./repeat 20 hello

 */


#include <stdio.h>

#include <string.h>

#include <stdlib.h>


int main(int argc, char **argv)

{

    long count = strtol(argv[1], NULL, 10);

    char *word = argv[2];

    size_t length = strlen(word);


    char *buffer = calloc(count, length + 1); // length+1 so we can add a newline

    for (size_t i = 0; i < count; i++) {

        char *destination = &buffer[i * (length + 1)];

        strcpy(destination, word);

        buffer[i * (length + 1) + length] = 10;

    }

    buffer[count * (length + 1)] = '\0';

    printf("%s", buffer);

    free(buffer);

}



1. 프로그램에 count inpu 으로 –1 이 주어지면, calloc 으로 얼마나 많은 메모리가 할당 되어야 하죠??


2. 위 코드에서 오류가 4개 있다고 하는데, 뭐뭐 있나요??





profile_image 익명 작성일 -

1. 프로그램에 count inpu 으로 –1 이 주어지면, calloc 으로 얼마나 많은 메모리가 할당 되어야 하죠?

-1이 주어지면 더 이상 프로그램을 진행하면 안되고 종료해야 합니다.

2. 위 코드에서 오류가 4개 있다고 하는데, 뭐뭐 있나요?

visual studio 2019에서 정상 동작하는 코드입니다. 참고하세요.

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

int main(int argc, char** argv)

{

if (argv[1] == NULL) // 인수로 넘어온 숫자가 없으면 종료.

return 0;

long count = strtol(argv[1], NULL, 10);

char* word = argv[2];

size_t length = strlen(word);

char* buffer = (char*)calloc(count, length + 1); // length+1 so we can add a newline

for (long i = 0; i < count; i++)

{

char* destination = &buffer[i * (length + 1)];

strcpy_s(destination, i*(length+1), word);

buffer[i * (length + 1) + length] = 10;

}

buffer[count * (length + 1)] = '\0';

printf("%s", buffer);

free(buffer);

}

[c언어] calloc에 관한 질문입니다.

얼마전부터 c언어를 독학으로 시작한 학생입니다. calloc을 이용한 메모리 할당을 공부하고 있는데 잘 모르는 부분이 있어서 질문드...

C언어 지뢰 찾기 질문

... C언어를 첫 언어로 배우고 있는... 지뢰 찾기 문제를 풀다가, 비쥬얼... 비표시 오류(Suppression) 상태 경고 C6031 반환 값이...

c언어 동적할당 malloc,calloc

저희가 동적할당할때 malloc이나 calloc을 쓰는데... 그래도 오류없이 잘 구동이 되고 문제가... 전꼭써야하는줄 알앗는데 안써도 되는거같아서 질문합니...

c언어 오류 질문입니다.

... 실행은 잘되는데 자꾸 오류가 뜹니다.. 무시 누르면 정상적으로... pointer = calloc(n, sizeof(int)); for (int i = 0; i < n; i++) { printf("pointer[%d]: ", i)...